How to implement behavior subject using service in Angular 8

后端 未结 4 694
借酒劲吻你
借酒劲吻你 2021-01-02 06:32

I\'m new to Angular and I\'m having an issue.

I\'m creating an app with several sibling components. When I update a value in one component other components don\'t u

4条回答
  •  [愿得一人]
    2021-01-02 06:58

    Here's how to solve your problem using a behavior subject:

    @Injectable()
    export class CoachService {
      apiURL = environment.apiURL;
    
      constructor(private http: HttpClient) { }
    
      updateProfile(info, token, us_id): Observable {
        return Observable.create((behaviorSubject: BehaviorSubject) => {
          const requestData = {
            token: token,
            us_id: us_id,
            us_lang: info.us_lang,
            us_firstname: info.us_firstname,
            us_lastname: info.us_lastname,
            us_sex: info.us_sex,
            us_birthdate: info.us_birthdate,
            us_national_number: info.us_national_number,
            us_email: info.us_email,
            us_gsm: info.us_gsm,
            online_profile: info.online_profile,
            us_address: info.us_address,
            us_zip: info.us_zip,
            us_city: info.us_city,
            country: {
              id: info.country.id
            }
          };
          const url = [this.apiURL, '/coach/update_profile'].join('');
    
          return this.http.post(url, requestData).subscribe(
            data => {
              behaviorSubject.next(data);
            },
            err => {
              behaviorSubject.error(err);
              if (err && err.status === 401) {
                // Do some err handling
              }
            }
          );
        });
      }
    
    }
    

    Now when you want to post data and subscribe to the result of your Behavior Subject from, say to the in the component you have here, you simply:

     updateCoordonees() {
      this.coachService.updateProfile(this.infos_profile, this.token, this.us_id)
        .subscribe((data: any) => {
    
          if (data.success && data.msg != null) {
            // do something on success
          }
    
        },
          (err) => {
            // do some err handling
          });
    } 
    
    

提交回复
热议问题