所以最近我学到了一些学科,我正在尝试在一个个人项目中使用它们。我有一个服务,它从json文件中获取数据,并将其转换为“条款”类型。文章是一个自定义类,它保存博客文章上的信息。
我的最终目标是获取这个文章数组,然后当我按+按钮时,它会向当前列表中添加一个新的空白文章,视图应该通过显示带有一些默认值的空白文章来表示它。这不会保留(保存到json)新的空白文章,而只是将其添加到当前列表中,以便视图更新并显示它。储蓄将在稍后到来。
我不能为了我的一生让这件事起作用。所有的文章都正确地显示在我的“文章列表”页面上,但是手动地将一个空白的文章推到它上似乎什么都不做。
这是我的服务文件
@Injectable()
export class ArticleService {
headers: Headers;
options: RequestOptions;
articles: ReplaySubject<Article[]>;
private url = 'data/articles.json';
constructor(private http: Http) {
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.options = new RequestOptions({ headers: this.headers });
this.articles = new ReplaySubject<Article[]>();
}
/**
* fetch a list of articles
*/
getArticles(): Observable<Article[]> {
// no articles fetched yet, go get!
return this.http.get(this.url, this.options)
.map(response => <Article[]>response.json())
.do(data => this.articles.next(data))
.catch(this.handleError);
}
/**
* add a new article to the list
* @param article
*/
addArticle(article: any): void {
this.getArticles().take(1).subscribe(current => {
//
//
// THIS WORKS. this.articles is UPDATED successfully, but the view doesn't update
// IT ALSO LOOKS LIKE this.articles may be being reset back to the result of the get()
// and losing the new blank article.
//
//
current.push(article);
this.articles.next(current);
});
}
...
}我有一个列表组件来更新列表,如下所示:
export class ArticleListComponent implements OnInit {
articles: Article[];
public constructor(private articleService: ArticleService) { }
ngOnInit(): void {
this.getArticles();
}
getArticles(): void {
this.articleService.getArticles().subscribe(articles => this.articles = articles);
}
}以及另一个创建新空白文章的组件:
export class CreatorComponent {
articles: Article[];
public constructor(private articleService: ArticleService) { }
/**
* add a new empty article
*/
add(): void {
let article = {};
article['id'] = 3;
article['author'] = "Joe Bloggs";
article['category'] = "Everyday";
article['date'] = "November 22, 2017"
article['image'] = "/assets/images/post-thumb-m-1.jpg";
article['slug'] = "added-test";
article['title'] = "New Via Add";
article['content'] = "Minimal content right now, not a lot to do."
this.articleService.addArticle(article);
}
}我可以进行调试,而且服务上的this.articles属性似乎是用新的空白文章更新的,但是视图没有改变,我也不能确定,但似乎这篇文章一添加就丢失了。是否可观察到的重复http和清洗文章列表再次干净?
发布于 2017-11-24 18:03:34
实际上,您还没有订阅您对显示组件感兴趣的主题。您只订阅http调用,该调用填充您感兴趣的主题,然后终止。试着像这样做:
private articleSub: Subscription;
ngOnInit(): void {
this.articleSub = this.articleService.articles.subscribe(articles => this.articles = articles);
this.articleService.getArticles().subscribe();
}
ngOnDestroy() { //make sure component implements OnDestroy
this.articleSub.unsubscribe(); // always unsubscribe from persistent observables to avoid memory leaks
}https://stackoverflow.com/questions/47478111
复制相似问题