简体   繁体   中英

Access my returned data from an RxJs Observable method call

(NEWB) How can I modify my updateUserProfile() Observable method in my service , so that I can get access to the returned data? I would like to set the values of my user in my service , and not in my component . Is there perhaps an additional callback function or operator I can use?

This is my User Object:

  user: User = {
    user: {
      first_name: '',
      last_name: '',
      id_number: '',
      email: '',
      password: '',
      phone: '',
      notes: '',
      ricaAddress: {
        street_number: '',
        street_name: '',
        building_name: '',
        floor_level: '',
        unit_number: '',
        suburb: '',
        city: '',
        province: '',
        postal_code: '',
        country: ''
      }
    }
  };

This is my updateProfile() call in my component :

  updateProfile() {
    this.userService
      .updateUserProfile(this.user)
      .subscribe(
        response => {},
        err => this.handleError(err),
        () => console.log('complete')
      );
  }

This is the updateUserProfile() method in my service I would like to modify :

  updateUserProfile(user): Observable<any> {
    const httpOptions2 = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        apiKey: 'xEr4slh6wdngI-imBb9t8sm4JLY-e1yQz7Tmo7S2A',
        key: '6f4962c7-0706-4cf7-b7ce-0b7dc75fcc57',
        Authorization: this.userToken
      })
    };

    return this.http
      .put(this.apiUrl + 'users' + 'user_id', user, httpOptions2)
      .pipe(catchError(this.handleError));
  }

Thank you!

You could add the map pipe in order to return a new, updated, object. In your service:

return this.http
  .put(this.apiUrl + 'users' + 'user_id', user, httpOptions2)
  .pipe(
    map(response => {
      // return a new object from here
    }),
    catchError(this.handleError)
  );

The return value of map 's callback can directly be accessed in your component then.

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