页面检测不到变化?

问题描述 投票:0回答:1

大家好。请问我有一个页面,绑定了一个变量的内容。但是我发现当变量发生变化时,页面并没有更新.除非我导航到另一个页面,然后在变化反映之前返回。请我需要你的帮助。我需要你的帮助,谢谢

我的编辑页/ 使用离子模式弹出/本页面更新用户数据

 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);
    }
    )
  });
angular ionic4
1个回答
0
投票

你在页面的构造函数中的方法只在类第一次构造时即页面加载时触发一次,这就是为什么你需要做一次重载来使它再次触发。

你需要做的是在服务中使用一个Subject并在其中存储数据,然后在个人资料页面中订阅它。

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方法,任何订阅profileSubject的东西都会在数据可用时获得更新的数据,即你在应用中的任何地方调用getUserInfo,新的数据就会推送给任何已经订阅的东西。

还有BehaviorSubject,它的作用几乎完全相同,但总是有最后一块可用的数据,所以新的订阅者总是在它订阅的时候收到一些东西,而不是必须等待。它可能很有用。

此外,保持构造函数的精简,大多数你想在页面加载时启动的代码应该在ngOnInit中进行,以确保在代码试图访问它时,所有的东西都是可用的。这在构造函数中是无法保证的。

希望能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.