angular - 对 Observable 的订阅永远不会触发

标签 angular observable angular2-services angular-cli

我使用 Angular-CLI 1.0.0-beta.18(昨天更新)创建了一个项目。我正在尝试检测组件中服务的更改。

  • 我在服务中创建了一个可观察对象
  • 我从组件订阅它
  • 订阅永远不会在更新时触发:/

我尝试实现 this answer 中的解决方案, this Plunkrthis 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/

相关文章:

angular - Ionic 4 防止缩短 prod 构建的类名

javascript - 添加自定义标题以提交表单

angular - 如何异步订阅用于candeactivate Guard的matdialog服务?

angular2 NgFor 仅支持绑定(bind)到 Iterables,例如 Arrays

angular - 如何修复 Angular 2 `Uncaught (in promise): TypeError: Cannot read property ' query' of null`?

Angular HttpClient 将 header 附加到 HttpHeaders

angular - RxJs难题:共享流并在有新订阅时有条件地重试

angular - Angular2 中的 ViewProvider 和 Services 之间的区别?

http - 如何从 http.request() 中正确捕获异常?

rest - 1 :N or N:1 relations of two objects in Angular2 as observables from a http request