2016-11-25 34 views
0

我有一篇文章類定義,像這樣:角2打字稿:域()不是一個函數

export class Article { 
    id : number; 
    isanon : boolean; 
    title: string; 
    link: string; 
    text: string; 
    subverse : string; 
    userID : string; 
    votes: number; 

    constructor(title: string, link: string, subverse : string, text : string, userID : string, votes?: number) { 
    this.title = title; 
    this.link = link; 
    this.text = text; 
    this.subverse = subverse; 
    this.userID = userID; 
    this.votes = votes || 0; 
    } 

    log() : void{ 
    console.log("Title: " + this.title + " Link: " + this.link + " subverse: " + this.subverse); 
    } 

    domain(): string { 
    try { 
     const link: string = this.link.split('//')[1]; 
     return link.split('/')[0]; 
    } catch (err) { 
     return null; 
    } 
    } 

    voteUp(): void { 
    this.votes += 1; 
    } 

    voteDown(): void { 
    this.votes -= 1; 
    } 


} 

,我用觀察到的服務

export class HomeComponent implements OnInit { 
    articles : Article[]; 

從數據庫中獲取物品和...

this.service.GetArticles(this.subverseStr).subscribe((data)=>{ 
    this.articles = <Article[]>data; 
    }); 

但是,在我的HTML模板中,它不能識別domain()或任何其他TS函數。

<div class="meta">({{ article.domain() }})</div> 

當加載頁面時,我得到錯誤:

core.umd.js:2837 EXCEPTION: Error in app/article/article.component.html:15:20 caused by: self.context.article.domain is not a function 

它並認識到它作爲一個功能,如果我硬代碼我的文章[],它並認識到成員變量。任何想法是怎麼回事?謝謝。

+1

請提供'GetArticles'和其他相關部分的代碼。根本不明顯,'data'是'Article'實例的數組,'{{article ...'引用'Article'實例並不明顯。 [MCVE](http://stackoverflow.com/help/mcve)是必要的。 – estus

+0

GetArticles和其他代碼可以在這裏找到:https://github.com/claysmith/hackerspulse/blob/master/wwwroot/app/services/app.service.hackerspulse.ts –

+1

GetArticles返回解析的JSON。這不是'文章'。並且不能有'域名'方法。 – estus

回答

1

GetArticles回報解析JSON,它是從res.json()一個普通的對象,而不是實例的數組Article。所以它不能有domain方法。

<Article[]>data欺騙式打字系統,所以Typescript認爲它是Article[]並且不會警告類型不匹配。

這取決於究竟是從服務器返回的,應該像

GetArticles(subverse : string) : Observable<Article[]> 
{ 
    return this.http.get(...) 
    .map(res => { 
     let data: any = res.json(); 
     let dataArr: any[] = Object.values(data); 

     return dataArr.map(({ title, link, ... }) => { 
     return new Article(title, link, ...); 
     }); 
    }) 
    .catch(this.handleError); 

} 

我建議移動由Article和JSON響應和共享屬性(titlelink,...)來通用的TypeScript接口,這可以使類型更緊密。

0

嘗試不帶()。 就像是:

{{arcticle.domain}} 

這基本上是一個指針到您的功能和Angular2將設法調用該函數

+0

當我嘗試沒有括號時,它只是空的。像空白字符串。 –

+0

@estus當我在課堂上將它定義爲這樣的時候,爲什麼它不是一個函數? –

+0

@ClaySmith因爲你從'GetArticles'獲得的東西不是'Article'類的實例。它是'res.json()'中的普通對象。你用'數據'欺騙了輸入系統,所以Typescript認爲它是'Article []',並且不會警告類型不匹配。 – estus