javascript - 如何使用 Behaviorsubject 检测变化

标签 javascript angular typescript rxjs observable

今天是个好日子。请我在使用 BehaviorSubject 时遇到问题.我正在尝试在获取/更新用户信息的共享服务中使用行为主题。我希望当用户数据更新时,订阅共享服务的其他组件也将更新。

服务.ts

  private userData= new BehaviorSubject<any>([]);
  data = this.userData.asObservable();


   customerData: any;


// this gets user data
getUserInfo(id){
  this.apiUrl = ` ${this.siteUrl}customers/${id}`;

  this.customerData = this.http.get(this.apiUrl);

   this.userData.next(this.customerData);
   return this.customerData;

}

//Update user data

updateCustomerData(id, customerDataUpdated){
  let headers = new HttpHeaders ({
    "Content-Type" : "application/json"
  });
  this.apiUrl = `${this.siteUrl}customers/${id}`;

  return new Promise((resolve, reject) => {
    this.http.put(this.apiUrl, customerDataUpdated, {headers} ).subscribe(
      response => {
        resolve(response);

        this.userData.next(this.customerData);

    },
    error => {
      resolve(error);

    }
    )
  });

Profile.ts

请告诉我这里如何使用 BehaviorSubject,以便如果订阅共享服务的任何组件有任何更新,该组件也将被更新。谢谢
 customerData: any;  



  constructor( private WC: Service){
   }

     ngOnInit() {
       // get authenticated user id
        this.isUserLoggedIn = localStorage.getItem('currentUserId');


         this.WC.getUserInfo(this.isUserLoggedIn).subscribe((data)=>{
          this.customerData = data;  
        });


      }

编辑页面
  // Update user info
  async updateMethod(){

    let loading = await this.loadingCtrl.create({
      message: 'Updating...'
     });

     loading.present();
    this.isUserLoggedIn = localStorage.getItem('currentUserId');

    let customerDataUpdated = {
      "first_name": `${this.user.first_name}`,
      "last_name": `${this.user.last_name}`,
      "email": `${this.user.email}`,
      "username": `${this.user.username}`,
      "billing": {
     //   "first_name": `${this.user.billing.phone}`,
     //   "last_name": `${this.user.value.billing_last_name}`,
        "address_1": `${this.user.billing.address_1}`,
      //  "address_2": `${this.user.value.billing_address_2}`,
      //  "postcode": `${this.user.value.billing_postcode}`,
      //  "email": `${this.user.value.billing_email}`,
       "phone": `${this.user.billing.phone}`
      },

    }


   console.log('new update', this.user);  
   //update user data
   this.WC.updateCustomerData(this.isUserLoggedIn, customerDataUpdated).then((data)=>{


    this.changedetector.detectChanges();
      loading.dismiss();  


     });  
  }


  }

最佳答案

让我解释一下,你想得到getUserInfo取决于 http 的用户 ID称呼。因此它只被触发一次,即使它是一个可观察的。
尝试:

service.ts

private userData= new BehaviorSubject<any>([]);
userInfo$ = this.userData.asObservable();

// this gets user data
getUserInfo(id){
  this.apiUrl = ` ${this.siteUrl}customers/${id}`;
  return this.http.get(this.apiUrl).pipe(switchMap(userData) => {
     this.userData$.next(userData);
     return this.userInfo$;
  }) 
}

private fetchUserInfo(id){
  this.apiUrl = ` ${this.siteUrl}customers/${id}`;
  this.http.get(this.apiUrl).subscriber(data =>{
    this.userData$.next(userData);
  })
}

//Update user data

updateCustomerData(id, customerDataUpdated){
  let headers = new HttpHeaders ({
    "Content-Type" : "application/json"
  });
  this.apiUrl = `${this.siteUrl}customers/${id}`;
  return this.http.put(this.apiUrl, customerDataUpdated, {headers}).pipe(
      tap(response => this.fetchUserInfo(id))
    )
  });


中进行更改编辑-page.component.ts 相应地为 updateCustomerData因为它不再是一个 promise 。

注意事项:如果您使用 userInfo$并通过其他一些 id进入 getUserInfo()那么它会影响你的Profile.ts成分。因为它们共享共同的 observable。

关于javascript - 如何使用 Behaviorsubject 检测变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61679094/

相关文章:

javascript - 为关闭声明函数两次?

javascript - 时间间隔 Angular 自动刷新

angular - 如何上传自定义字体并在 angular 6 中动态使用它

angular - 如何在 Angular 中使用 MediaElement

reactjs - React Hook 在状态更改后不会重新渲染 array.map

javascript - 多个js文件中的ipcRenderer监听器未调用一个渲染器进程/主窗口

javascript - 使用 php 动态更改选择选项

angular - 错误 错误 : NbFormFieldComponent must contain [nbInput]

angular - 是否可以更改 3rd 方模块的样式?

reactjs - TypeScript/JSX 中 React.createElement 的正确语法