next()不通知subscribe()

时间:2018-01-09 13:54:51

标签: javascript angular rxjs

我有一些服务

isDocAdd: Subject<boolean> = new Subject<boolean>();

addDocument(header) {
        return this.http.post(this.addHl7DocumentUrl, header)
            .map((response: any) => { if (response.status === '404') {
                    this.isDocAdd.next(true);
                }
                else {
                    this.isDocAdd.next(false);
                }
                return response;
            })
            .catch((error: Error) => {
                console.error('Error:', error);
                return Promise.reject(error.message || error);
            });
    }

和在component.ts中订阅()通知

subscription: Subscription;
message;

constructor(private documentService: DocumentService) {
    this.subscription = this.documentService.isDocAdd.subscribe(val => { this.message = val; });

}

在方法addDocument()中设置this.isDocAdd.next(val),但不通知组件有关更改,且subscribe()方法不执行。

3 个答案:

答案 0 :(得分:1)

private isDocAdd= new Subject<boolean>();
isDocAdd$ = this.isDocAdd.asObservable();
addDocument(header) {
        return this.http.post(this.addHl7DocumentUrl, header)
            .map((response: any) => { response.status === '404') {
                    this.isDocAdd.next(true);
                }
                else {
                    this.isDocAdd.next(false);
                }
                return response;
            })
            .catch((error: Error) => {
                console.error('Error:', error);
                return Promise.reject(error.message || error);
            });
    }

并在component.ts中

subscription: Subscription;
message;

constructor(private documentService: DocumentService) {
    this.subscription = this.documentService.isDocAdd$.subscribe(val => { this.message = val; });
}

答案 1 :(得分:1)

这是因为您的组件是在服务之后创建的。

这意味着,您的组件不知道您的主题,因此您在没有订阅的情况下拨打下一个。

一种解决方案是改为使用BehaviorSubject

isDocAdd: BehaviorSubject<boolean> = new BehaviorSubject<boolean>();

它的工作方式完全相同,但BehaviorSubject会在您实例化时通知其观察者(即使该值为null,因此请测试!)

答案 2 :(得分:0)

需要从您的主题创建一个observable才能订阅它。使用asObservable

isDocAdd: Subject<boolean> = new Subject<boolean>();
onChanged: Observable<boolean> = this.isDocAdd.asObservable();

现在订阅onChanged

this.subscription = this.documentService.onChanged.subscribe(val => { this.message = val; });