Angular 2 http get使用Asp.net核心MVC
我想知道如何在Angular 2中获取数据并将其放在javascript中。我已经看过了《英雄教程》,下面是我到目前为止的想法Angular 2 http get使用Asp.net核心MVC,angular,Angular,我想知道如何在Angular 2中获取数据并将其放在javascript中。我已经看过了《英雄教程》,下面是我到目前为止的想法 我在构造函数中创建了一个带有http var的服务 我在服务中创建了一个函数来获取文章 GetArticles(subverse : string) : Observable<Article[]> { console.log("GetArticles URL: " + this._getArticlesUrl + "/?subverse="+subve
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);
}
这是我的文章课:
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);
articlesO:可见;
条款:第[]条;
this.articlesO=this.service.GetArticles(this.subversisestr);
this.articlesO.forEach(a=>this.articles=a);
但是我的this.articles
在代码中保持未定义。我应该如何读取URL json并将其转换为我的文章[]
谢谢你的帮助
谢谢 一个可观察的事物就像一个承诺,但就像它的一个流版本。您可以在此处找到承诺与可观测的详细信息:
对于您的问题,您需要订阅可观察到的,以便激发它
像这样:
this.service.GetArticles(this.subverseStr).subscribe( (data)=>{
console.log(data);
//do something with the returned data.
this.articles = data;
});
@ClaySmith在chrome的网络选项卡中,服务器返回给您的是什么?我通过从json代码中删除body.data来实现。服务器在我的原始帖子中返回URL响应。我想它起作用了!非常感谢您的快速回复。:)@克莱史密斯:啊,没问题,很高兴你弄明白了:)
this.service.GetArticles(this.subverseStr).subscribe( (data)=>{
console.log(data);
//do something with the returned data.
this.articles = data;
});