在学习 Angular 2 时,我使用了一个 observable 通过 API 获取一些数据。像这样:
getPosts() {
return this.http.get(this._postsUrl)
.map(res => <Post[]>res.json())
.catch(this.handleError);
}
我的帖子模型看起来是这样的:
export class Post {
constructor(
public title: string,
public content: string,
public img: string = 'test') {
}
我面临的问题是 map 操作符不会对 Post 模型做任何事情。例如,我尝试为 img 值设置默认值,但在 View post.img 中什么也没显示。我什至用其他模型 (Message[]) 更改了 Post[] 并且行为没有改变。有人可以解释这种行为吗?
最佳答案
当我想在模板中使用计算属性时,我遇到了类似的问题。
我在这篇文章中找到了一个很好的解决方案:
http://chariotsolutions.com/blog/post/angular-2-beta-0-somnambulant-inauguration-lands-small-app-rxjs-typescript/
您在模型上创建一个静态方法,该方法采用对象数组,然后从映射函数调用该方法。在静态方法中,您可以调用已经定义的构造函数或使用复制构造函数:
映射方法
getPosts() {
return this.http.get(this._postsUrl)
.map(res => Post.fromJSONArray(res.json()))
.catch(this.handleError);
}
现有构造函数
export class Post {
// Existing constructor.
constructor(public title:string, public content:string, public img:string = 'test') {}
// New static method.
static fromJSONArray(array: Array<Object>): Post[] {
return array.map(obj => new Post(obj['title'], obj['content'], obj['img']));
}
}
复制构造函数
export class Post {
title:string;
content:string;
img:string;
// Copy constructor.
constructor(obj: Object) {
this.title = obj['title'];
this.content = obj['content'];
this.img = obj['img'] || 'test';
}
// New static method.
static fromJSONArray(array: Array<Object>): Post[] {
return array.map(obj => new Post(obj);
}
}
如果您使用支持代码完成的编辑器,您可以更改
obj
的类型。和 array
Post
的参数:export class Post {
title:string;
content:string;
img:string;
// Copy constructor.
constructor(obj: Post) {
this.title = obj.title;
this.content = obj.content;
this.img = obj.img || 'test';
}
// New static method.
static fromJSONArray(array: Array<Post>): Post[] {
return array.map(obj => new Post(obj);
}
}
关于angularjs - Angular 2 observable 不是 'map' 来建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36150709/