0

I am trying to create routes for user profiles in Angular. The snapshot, no-observable approach, almost behaves like I want; where the getUser() function outputs the user object in my template. It falls short in that I can't update the user once I go to it. I think I need the switchMap approach so that I can regenerate the instance for different users in the same session.

What do I need to do to make the user variable available in my template with switchMap? In both cases the router works (goes to the generic template), but with switchMap, the user object doesn't return anything in the template.

constructor(private apiService: ApiService,
    private form_builder: FormBuilder,
    public authService: AuthService,
    private route: ActivatedRoute,
    private router: Router) 

ngOnInit(): void {
    // const auth0_user_id_synced = this.route.snapshot.paramMap.get('auth0_user_id_synced')!;
    // this.getUser(this.route.snapshot.paramMap.get('auth0_user_id_synced'));

    this.user$ = this.route.paramMap.pipe(
      switchMap((params: ParamMap) =>
        this.apiService.getUser(params.get('auth0_user_id_synced')!))
    );
        // this.getUser('auth0_user_id_synced');
  }

  getUser(user_pk: any) {
    this.apiService.getUser(user_pk)
    .subscribe((user:any) => {this.user = user;
  },
    (error:any) => this.errorMessage = <any>error);
  }

I tried both of the below in the template.

  <h2>Welcome {{user.first_name}}</h2>
and 
  <h2>Welcome {{user$.first_name}}</h2>
Eric Kumar
  • 21
  • 3

1 Answers1

2

Your assignment code looks to be good.

ngOnInit(): void {
    this.user$ = this.route.paramMap.pipe(
      switchMap((params: ParamMap) =>
        this.apiService.getUser(params.get('auth0_user_id_synced')!))
    );
  }

In order to use user$ you need to keep in mind that this is an observable, it's not an actual value that you can use freely. To do that in .ts, you just use this.user$.subscribe(...) to get access to the values emitted by this observable.

For getting the value of an observable in the template (which seems to be what you need), you can use the async pipe that does the subscription for you and also updates the template whenever the observable emits a new value:

<h2>Welcome {{(user$ | async).first_name}}</h2>
Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29
  • Awesome! Thanks for bringing clarity here. For completeness, I changed the .ts as follows: ``` ngOnInit(): void { this.user$ = this.route.paramMap.pipe( switchMap((params: ParamMap) => this.apiService.getUser(params.get('auth0_user_id_synced')!)) ); this.user$.subscribe((user:any) => {this.user = user; }, (error:any) => this.errorMessage = error); } } ``` – Eric Kumar Jun 21 '22 at 17:05