S S
S S

Reputation: 1513

How to get data stored as subject rxjs

I am working on displaying the details of event clicked. I have stored all the events inside an array.

When the user clicks on the event then its id is passed which checks inside the array and it passes the result into service.

 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]);

    }

service

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

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

Now in my article/id page. I am not being able to retrieve this passed array.

I have following code

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

Upvotes: 0

Views: 447

Answers (1)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

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

You already added BehaviorSubject tag. So use it. Also, getMessage(): Observable<any> { doesnt do anything except returns Observable. Feels redundant:

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

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

And

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

Upvotes: 1

Related Questions