【问题标题】:How to use Behaviorsubject to detect change如何使用 Behaviorsubject 来检测变化
【发布时间】:2020-05-08 12:23:16
【问题描述】:

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

Service.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();  


     });  
  }


  }

【问题讨论】:

  • 您如何更新Component1 中的数据??你能给我们看看吗。我看到的只是订阅ngOnInit
  • 好的,我会更新代码
  • 我已经更新了。谢谢
  • 试试我的答案,让我知道。我没有运行这个,所以如果你遇到任何问题,请告诉我。诀窍是使用switchMap
  • 如果它有效,请随时投票

标签: javascript angular typescript rxjs observable


【解决方案1】:

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

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))
    )
  });

edit-page.component.ts 中相应地为 updateCustomerData 进行更改,因为它不再是一个承诺。

注意:如果您使用userInfo$ 并将其他一些id 传递给getUserInfo(),那么它将影响您的Profile.ts 组件。因为它们共享共同的 observable。

【讨论】:

    【解决方案2】:

    请试试这个,

    customerData: any;  
    
    
    constructor( private WC: Service){ }
    
    ngOnInit() {
    //this will triger when data is changing
    this.WC.data.subcribe(res => {
    
    });
    
    }
    

    【讨论】:

    • 感谢您的努力,但我如何将其与获取用户信息的方法同步..." this.WC.getUserInfo(this.isUserLoggedIn).subscribe((data)=>{ this.customerData = 数据;});"
    猜你喜欢
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2016-08-16
    • 2022-07-11
    • 2021-12-31
    • 2015-08-08
    相关资源
    最近更新 更多