Changes done in one component view doesn't reflect in another component view in angular 4

后端 未结 1 661
盖世英雄少女心
盖世英雄少女心 2021-01-17 04:20

Here I am changing some data in one component ex: change user profile picture of one module and the same profile picture should be reflected in another component of some oth

相关标签:
1条回答
  • 2021-01-17 04:45

    I would recommend you to store the user in some service (user-service.) When Component1 updates the user profile URL, update the user in the user-service. Make sure both the components are subscribed to the user in the user-service. This way the Component2 would always see the same user as Component1

    Sample code

    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;
          });
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题