我使用 Angular-CLI 1.0.0-beta.18(昨天更新)创建了一个项目。我正在尝试检测组件中服务的更改。
- 我在服务中创建了一个可观察对象
- 我从组件订阅它
- 订阅永远不会在更新时触发:/
我尝试实现 this answer 中的解决方案, this Plunkr和 this cookbook ,没有骰子。
这是服务:
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { Article } from './article';
@Injectable()
export class ArticleService {
// Placeholder for article's
articles: Article[] = [
{ _id: 1, title: "Article 1", text: "Text for article 1", created: new Date() },
{ _id: 2, title: "Article 2", text: "Text for article 2", created: new Date() }
];
// Observable openArticle source
private _openArticleSource = new ReplaySubject<Article>(1);
// Observable openArticle stream
openArticle$ = this._openArticleSource.asObservable();
// Simulate GET /articles/:_id
getArticleById(_id: number): Article {
let article = this.articles
.filter(article => article._id === _id)
.pop();
console.log("Pushing article to observable : ", article) // This gets logged, along with the article
this._openArticleSource.next(article); // Should trigger the subscription, but doesn't
return article;
}
}
这是监听组件:
import { Component } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ArticleService } from '../article.service';
@Component({
selector: 'column-open-article',
templateUrl: './column-open-article.component.html',
providers: [ArticleService]
})
export class ColumnOpenArticleComponent {
openArticle;
subscription: Subscription;
constructor(private articleService: ArticleService) {
this.subscription = articleService
.openArticle$
.subscribe(article => {
console.log("Subscription triggered", article); // Never gets logged
this.openArticle = article; // Never gets updated
})
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
console.log("Unsubscribing")
this.subscription.unsubscribe();
}
}
然后我从另一个组件调用 getArticleById(1)
,我可以在控制台中看到 “将文章推送到可观察的”
,因此可观察的已更新,但没有更新t 触发订阅。
如果我将订阅直接放入服务中,它会毫无问题地触发,并且我可以在控制台中看到“订阅已触发”
。
但是如果我将相同的代码放入组件中,它就不起作用。
有什么想法吗?
最佳答案
看起来您有多个 ArticleService
实例。
不要在每个组件上提供ArticleService
,因为这样每个组件实例都会获得一个新的ArticleService
实例。
要么在公共(public)父组件上提供它,以便两者从注入(inject)的父组件中获取相同的实例
或
在@NgModule{providers: [ArticleService]}
中提供它,然后它将在应用程序根范围内提供,并且注入(inject)ArticleService
的每个组件和服务都将获得注入(inject)相同的实例。
关于angular - 对 Observable 的订阅永远不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195416/