如何获取存储为主题rxjs的数据

时间:2019-06-03 10:37:54

标签: rxjs angular6 behaviorsubject

我正在显示单击事件的详细信息。我已将所有事件存储在数组中。

当用户单击事件时,将传递其ID,该ID在数组内部进行检查,并将结果传递给服务。

 showDetail(id){
     let obj = this.events;

        let newArr =  Object.values(obj);

        let result = newArr.filter(function(el)  {
            return el["id"] == id; 
        });

    this.articleService.sendMessage(result);
        let url = `/article/${id}`;
        this.router.navigate([url]);

    }

服务

private detailSubject = new Subject<any>();
sendMessage(formData: any) {
        this.detailSubject.next({formData});
    }

    getMessage(): Observable<any> {
        return this.detailSubject.asObservable();
    }

现在在我的文章/ ID页面中。 我无法检索此传递的数组。

我有以下代码

ngOnInit() {
    this.articleService.getMessage().subscribe(
        res => {
            this.loadArticleDetail(res["formData"]);
        },
        error => {
            console.log("Error loading data");
        }
    );
}

1 个答案:

答案 0 :(得分:1)

this.articleService.sendMessage(result); // <-- Subject.next()
let url = `/article/${id}`;
this.router.navigate([url]); // <-- Subject.subscribe() after Subject.next(), so value already emitted

您已经添加了BehaviorSubject标签。因此使用它。另外,getMessage(): Observable<any> {除了返回Observable以外不执行任何操作。感到多余:

private detailSubject = new BehaviorSubject<any>(null);
message$ = this.detailSubject.asObservable();

sendMessage(formData: any) {
        this.detailSubject.next({formData});
    }

ngOnInit() {
    this.articleService.message$.subscribe(...