Changing value in one component affects another

孤者浪人 提交于 2019-12-11 17:29:42

问题


I have an angular 6 application, which has a top bar and a content area below this. These are different component and I am currently developing the user profile page. Name of the user is also displayed in the top bar.

My problem is like whenever I have updated the user's name in EditUser page, it successfully saves, but the same is not updated on the top bar. In Vue.js, I can simply handle this with a Vuex store; but how can I handle this in Angular 6.

Any help would be much appreciated.


回答1:


Next time post a bit of code. Since there isn't, I'll show you how to do it with an example.

Let's assume we have two component, A and B. And the changes will be reflected on both of two components.

Service :

export class YourService{
  private data$ = new BehaviorSubject<string>(null);
  data = this.data$.asObservable();

  public setData(data: string){
    this.data$.next(data);
  }
}

Component A/B.html :

<div>{{something}}</div>

Component A/B.ts :

isAlive = true;
something: string;

constructor(
  private service: YourService
) { }

ngOnInit(){
  this.service.data
  .takeWhile(() => this.isAlive)
  .subscribe( res => {
    if(!!res){
      this.something = res;
    }
  });
}

    ngOnDestroy(){
      this.isAlive = false;
    }

Component that change the status:

export class AnotherComponent{
  constructor(
    private service: YourService
  ) { }

  private changeData(data: string){
    this.service.setData(data);
  }
}

Now everything is working fine. BehaviorSubject allow the communication between components. whenever the function changeData is fired, you will see the changes on both of your components.

takeWhile is for unsubscribing when the component die.

If you have more question, feel free to ask them to me and I will edit this answer.




回答2:


You can create service to exchange data between components. It could be UserService that provide access to current user information.

@Injectable()
export class UserService {
    user: UserInfo;
    // define user here (load from backend or somehow else)
}

In user-profile.component.ts

export class UserProfileComponent {

constructor(public userService: UserService) { }
}

user-profile.component.html

<input type="text" [(ngModel)]="userService.user.name">

In header.component.ts

export class HeaderComponent {

constructor(public userService: UserService) { }
}

header.component.html

<span>{{ userService.user.name }}</span>

So the anggular DI will create a singleton UserService and injects the same object to both components. And when you change it in any of them the changes will be shown in other.



来源:https://stackoverflow.com/questions/52382447/changing-value-in-one-component-affects-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!