对Observable的订阅永远不会触发

时间:2016-10-22 18:10:11

标签: angular observable angular2-services angular-cli

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

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

我尝试从this answerthis 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),我可以在控制台中看到"Pushing article to observable",因此observable已更新,但不会触发订阅。

如果我将订阅直接放在服务中,它会毫无问题地触发,我可以在控制台中看到"Subscription triggered"

但是如果我在组件中放置相同的代码,它就无法工作。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您似乎有 <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="http://sotd.us/jared_freese/NodeJS/jquery.validate.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script> <script src="http://sotd.us/jared_freese/NodeJS/flightscript.js"></script> 的多个实例。

不要在每个组件上提供ArticleService,因为这样每个组件实例都会获得一个新的ArticleService实例。

在公共父组件上提供它,以便从注入的父组件中获取相同的实例

ArticleService中提供它,然后它将在应用程序根范围提供andevery组件和注入@NgModule{ providers: [ArticleService]}的服务将获得注入的相同实例。