2016-11-25 211 views
1

我想知道如何获取Angular 2中的数据并将其放入JavaScript中。我看过英雄的教程,这是我到目前为止所做的。Angular 2 http获取使用Asp.net Core MVC

  1. 我在构造函数中

  2. 我创建的服务功能得到物品

    GetArticles(subverse : string) : Observable<Article[]> 
    { 
        console.log("GetArticles URL: " + this._getArticlesUrl + "/?subverse="+subverse); 
    
        return this.http.get(this._getArticlesUrl + "/?subverse="+subverse) 
          .map(this.extractData) 
          .catch(this.handleError); 
    } 
    
    private extractData(res: Response) 
    { 
        let body = res.json(); 
        return body.data || { }; 
    } 
    
    private handleError (error: Response | any) 
    { 
        // In a real world app, we might use a remote logging infrastructure 
        let errMsg: string; 
        if (error instanceof Response) { 
        const body = error.json() || ''; 
        const err = body.error || JSON.stringify(body); 
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
        } else { 
        errMsg = error.message ? error.message : error.toString(); 
        } 
        console.error(errMsg); 
        return Observable.throw(errMsg); 
    } 
    

不过,我不创建以http VAR服务不明白什么是可观察的,为什么我必须在这里使用它?

现在,这段代码实际上是调用我的网址和URL实际上返回文章数据为JSON

URL响应:

[{"id":1,"userID":"00d85571-e2d3-4817-8698-6aa1b184112b","title":"title","link":"http://google.com","text":"text","subverse":"home","votes":0,"isanon":false}] 

这里是我的文章类:

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

我问题是,我如何将这个URL响应放入我的javascript文章[]中?我试过

articlesO : Observable<Article[]>; 
    articles : Article[]; 

    this.articlesO = this.service.GetArticles(this.subverseStr); 

    this.articlesO.forEach(a => this.articles = a); 

但我this.articles停留undefined代码。我该如何读取URL json并将它变成我的Articles[]

任何帮助表示赞赏。

谢谢。

回答

1

可观察就像一个承诺,但像它的流版本。你可以找到关于承诺的详细信息VS这里观测:Angular - Promise vs Observable

而对于你的问题,你需要订阅以可观察到的,以火了。

像这样:

this.service.GetArticles(this.subverseStr).subscribe((data)=>{ 
    console.log(data); 
    //do something with the returned data. 
    this.articles = data; 
}); 
+1

@ClaySmith什么铬的网络选项卡中的服务器对您的回报? – echonax

+0

我通过从json代码中删除body.data来实现它。服务器在我的原始帖子中返回URL响应。我认为它正在工作!非常感谢您的快速回复。 :) –

+1

@ClaySmith啊没问题,很高兴你明白了:) – echonax