1
Angular-CLI 1.0.0-beta.18 (어제 업데이트 됨)으로 프로젝트를 만들었습니다. 구성 요소에서 서비스의 변경을 감지하려고합니다. 내가 this answer에서 솔루션을 구현하려고/ Observable에 대한 구독이 실행되지 않습니다
, 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; } }
가 감상 구성 요소입니다 : 여기
서비스입니다 그럼 난 다른 구성 요소에서
getArticleById(1)
전화, 나는 콘솔에"Pushing article to observable"
을 볼 수 있습니다, 그래서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(); } }
관찰 가능은 업데이트되지만 구독을 트리거하지는 않습니다.
서비스에 직접 가입하면 문제없이 실행되며 콘솔에
"Subscription triggered"
이 표시됩니다.하지만 구성 요소에 동일한 코드를 삽입해도 작동하지 않습니다.
아이디어가 있으십니까?
오 이런 식으로 작동합니다! 나는 서비스가 앵글 1과 같은 싱글 톤이라고 생각했다. 실제로 모듈 레벨에서 한 번, 모듈 레벨에서, 그리고 각 컴포넌트에서 가져와야한다. 잡았다. 이제 작동합니다. 정말 고마워요! –
그들은 공급자 당 싱글 톤입니다. 둘 이상의 공급자가있는 경우 하나 이상의 인스턴스가 생성됩니다. '@NgModule()'의 provider : []'는 모두 루트 범위로 끌어 올려집니다. 따라서 이러한 여러 공급자는 여전히 하나의 인스턴스가되지만 구성 요소 나 지시문의 공급자는 모든 구성 요소 나 지시문에 대해 다른 인스턴스를 갖습니다. 게으른로드 된 모듈은 자체 루트 범위를 갖습니다. –