0
votes

I am trying to use switchMap combined with template async pipe so I think I need to return an Observable. But this is just not working.

this.route.params.switchMap( (params: Params) => 
  this.course = this.courseService.get(params['id'])
);

I thought in the template

<div *ngif="course | async as c">
  {{c.name}}
</div>

should subscribe this observable and trigger the request to server but it seems not. What did I misunderstand here? The same approach seems ok with ngFor on Observable array.

Fixed this by, ( still confusing what switchMap does here, I steal it from somewhere):

this.route.params.subscribe( params => this.course = this.courseService.get(params['id']));

Anyone can explain, why switchMap not working in this case.

In my other project, this works:

this.route.params
      .switchMap((params: Params) => 
         this.journalService.getJournal(+params['id']))
      .subscribe( (journal) => {
        this.journal = journal;
      });
2
Is route.params subscribed?Max
that's the thing. I defined this.course as Observable and I used rsync pipe in the template. Do I still need to subscribe? how?Hao
I think this.route.params might also need to be subscribed, if it is not subscribed, the code inside switchMap won't run at all. You can try to add .subscribe() after switchMap. And I don't understand what you are using switchMap for.Max
Your question is helpful. I got it work by subscribing params. Maybe you can answer about when to use params.subscribe and when to use params.switchMap? This is my confusion here, still. Thanks a lot.Hao

2 Answers

1
votes

The problem comes from the switchMap.

switchMap expects to receive an observable but you're not returning an observable: this.course = this.courseService.get(params['id']).

You might try that instead:

this.course$ = this.route.params
  .map(params => params['id'])
  .switchMap(id => this.courseService.get(id));

And

<div *ngIf="course$ | async as c">
  {{c.name}}
</div>
0
votes

Here is a blog maybe helpful for you. According to this blog:

Observables are either hot or cold

If this plain Observable has no subscribers, it will not be triggered! The observable is said to be cold because it does not generate new values if no subscriptions exist.

switchMap is a operator which is supposed to be used to transform data coming from stream. You can learn all rxjs concepts on its official site.

Operators: are pure functions that enable a functional programming style of dealing with collections with operations like map, filter, concat, flatMap, etc.

Hope that can do some help.