简体   繁体   中英

Angular await service between components, Behavior Subject

I have an issue in my Angular web store when i refresh the window, i create a service that takes the user data from the server and then inject to the 'products' section with BehaviorSubject, my goal is to make just one request to the server:

 import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable({ providedIn: 'root' }) export class DataService { private userId = new BehaviorSubject<any>(''); currentUserId = this.userId.asObservable(); constructor() { } sendUserId(message: string){ this.userId.next(message) } }

This works fine but the problem is when i refresh the window in products section, in console i can see that the service takes the user data but when i getProducts() it throws an error, it seems like getProducts() makes the request before the service had the response, i need the user Id to make the products request. My question: Is there a way to await the response of BehaviorSubject and then make the getProducts() request?. This is the code in the products section:

 ngOnInit(): void { this._dataService.currentUserId.subscribe(userId => this.userId = userId); if(this.userId.length === 0){ this.userService.getUserProfile().subscribe( res => { this.userDetails = res['user']; this.userId = this.userDetails._id; this.getProducts(); }, err => { console.log(err); } ); } else { this.getProducts(); } }

As you can see, i do a condition to check if userId exists, if not i have to make a new user request, this fix the bug but i think there's a better way to solve this. Thanks in advance.

How about placing all your logic within the observer 's next function as below:

this._dataService.currentUserId.subscribe(userId => {
  if (userId.length === 0)
  {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res['user'];
        this.userId = this.userDetails._id;
        this.getProducts();
      },
      err => {
        console.log(err);
      }
    );
  } else
  {
    this.getProducts();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM