网页无法检测到更改?

时间:2020-04-21 22:48:37

标签: angular ionic4

大家好。请给我一个页面,该页面绑定到内容变量。但是,我注意到变量更改后页面不会更新。除非我导航到另一页并在更改反映出来之前返回。拜托我需要你的帮忙。谢谢

我的编辑页面 //正在使用离子模式弹出窗口 //此页面更新用户数据

 async updateUserData(){

    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": {

        "address_1": `${this.user.billing.address_1}`,
       "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();  

          setTimeout(()=>{
          this.modalCtrl.dismiss({
            'dismissed': true
          });
      }, 3000);       

     });

个人资料页面

// update on edit page does not reflect here unless I navigate to another tab and back

      constructor(private changedetector: ChangeDetectorRef, private WC: WoocommerceService,) {

    // this retrieve user data from api call    
         ngOnInit() {

   this.isUserLoggedIn = localStorage.getItem('currentUserId');
    this.WC.getUserInfo(this.isUserLoggedIn).subscribe((data)=>{
      this.customerData = data;  
    });


    this.WC.profileSubjects.subscribe((data) => {
 //    this.customerData = data;
     console.log('change update ', data);
  });

woocommerce.service.ts

    //getting authenticated users details from woocommerce

    getUserInfo(id){
      this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
      console.log('API url for retrive customer: ', this.apiUrl);
      this.customerData = this.http.get(this.apiUrl).pipe( retry(1),catchError(this.handleError) );
      return this.customerData;
    }


    // this update user data
        updateCustomerData(id, customerDataUpdated){
          let headers = new HttpHeaders ({
            "Content-Type" : "application/json"
          });
          this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
         // console.log('API url for retrive customer data: ', this.apiUrl);
          return new Promise((resolve, reject) => {
            this.http.put(this.apiUrl, customerDataUpdated, {headers} ).subscribe(
              response => {
                resolve(response);
                console.log('Customer Data Updated: ', response);
            },
            error => {
              resolve(error);
             console.log('Customer Data Updated failed ', error);
            }
            )
          });
        }


updateCustomerData(id, customerDataUpdated){
  let headers = new HttpHeaders ({
    "Content-Type" : "application/json"
  });
  this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
 // console.log('API url for retrive customer data: ', this.apiUrl);

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

        console.log('Customer Data Updated: ', response);
    },
    error => {
      resolve(error);
     console.log('Customer Data Updated failed ', error);
    }
    )
  });

1 个答案:

答案 0 :(得分:0)

您在页面构造函数中的方法仅在首次构造类时触发一次,即页面加载,这就是为什么您需要重新加载以使其再次触发的原因。

您需要做的是使用主题并将数据存储在服务中,然后在个人资料页面中订阅。

WooCommerceService代码:

import { Subject } from 'rxjs'; 

let profileSubject = new Subject<any>();

getUserInfo(id){
  this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}? 
    consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
    console.log('API url for retrive customer: ', this.apiUrl);
    this.customerData = this.http.get(this.apiUrl);

    // STORE WHATEVER DATA YOU WANT IN THE SUBJECT 
    this.profileSubject.next(this.customerData)
 .pipe(retry(1),catchError(this.handleError) );
   return this.customerData;
}

Profile page:

ngOnInit() {
     this.wc.profileSubject.subscribe(data => {
        // do something with the data
     }
}

现在,使用Subject方法,订阅profileProfile的所有内容都会获得更新的数据,即您可以从应用程序中的任何位置调用getUserInfo,并将新数据推送到已订阅的任何内容。

还有一个BehaviorSubject,其行为几乎完全相同,但始终具有最后可用的数据,因此新订户在预订时始终会收到一些东西,而不必等待。可能有用。

此外,请保持构造函数的精简性,您要在页面加载时触发的大多数代码都应放在ngOnInit中,以确保在代码尝试访问它时所有内容都可用。构造函数无法保证这一点。

希望有帮助。