【问题标题】:Changes done in one component view doesn't reflect in another component view in angular 4在一个组件视图中所做的更改不会在角度 4 中反映在另一个组件视图中
【发布时间】:2018-08-07 00:35:43
【问题描述】:

在这里,我正在更改一个组件中的一些数据,例如:更改一个模块的用户个人资料图片,并且相同的个人资料图片应该反映在其他模块的另一个组件中。这些不是父/子组件。 因此,我正在导入模块和特定组件。调用分配个人资料图片范围值的组件的函数。该功能被触发并且更改的 url 出现在控制台中,如果我在控制台中打印它。但没有反映在视图中。 我试过ChangeDetectorRefthis.ref.detectChanges(); 但它给出的错误是

core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for ChangeDetectorRef!
Error: No provider for ChangeDetectorRef!

还尝试了 Zone.run()。
但这对我不起作用。谁能帮忙。

 constructor(private appHeaderComponent: AppHeaderComponent) { }


//component 1 sending data
uploadProfilePicture = (event) => {
 if (this.profileFormData) {
     this.headerService.savePhoto(this.profileFormData, 'profile-pictures').then((saveProfilePhotoData) => {
         if (saveProfilePhotoData['status_code'] === 200) {
             this.appHeaderComponent.getUserImage(saveProfilePhotoData['result']['pictures'][0]['imageUrl']);
         }
     });
  }
 }


//component 2 Receiving data
getUserImage = (image) => {
 if (image) {
     this.userImage = image;
 } else {
     this.userImage = sessionStorage.profilePicture;
 }
}

【问题讨论】:

  • 你是如何定义你的 ChangeDetectorRef 的?应该是:constructor(private ref: ChangeDetectorRef){}
  • 是的。就像constructor(private ref: ChangeDetectorRef){}

标签: angular views provider angular2-changedetection


【解决方案1】:

我建议您将 user 存储在某个服务(user-service)中。当 Component1 更新用户配置文件 URL 时,更新用户服务中的用户。确保两个组件都订阅了用户服务中的用户。这样 Component2 将始终看到与 Component1

相同的用户

示例代码

export class UserService {

   public userReplaySubject = new ReplaySubject<User>(1);

   setUser(u: User){
     this.userReplaySubject.next(u);
   }
}

export class Component1 { 

  user: User;

  constructor(private userService: UserService) {
      // Will always have the latest user in the service
      this.userService.userReplaySubject.subscribe(user => {
         this.user = user;
      });
  }

  updateUserProfile(){
    //when the profile-url changes, update the user service
    this.userService.setUser(user);
  }
}


export class Component2 { 

  user: User;

  constructor(private userService: UserService) {
      // Will always have the latest user in the service
      this.userService.userReplaySubject.subscribe(user => {
         this.user = user;
      });
  }

}

【讨论】:

  • 我在另一个组件 ts 中获取数据,因为我将所需数据作为参数传递。我也可以通过打印在控制台中看到它。但不只是反映在视图中
  • 能否分享您的组件定义,包括模板
  • 所以你将一个组件注入到另一个组件中。我怀疑他们是同一个例子。您会在 AppHeaderComponent 中放置一个 console.log 并查看它被调用了多少次。从父容器中,您可以使用 @ViewChild(AppHeaderComponent) 获取对应用程序头组件的引用。我仍然建议使用单例服务,所有组件都将获得相同的服务实例。
猜你喜欢
  • 2020-03-25
  • 2017-07-12
  • 1970-01-01
  • 2017-10-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 2020-11-01
相关资源
最近更新 更多