更改一个组件中的值会影响另一个组件 [英] Changing value in one component affects another

查看:124
本文介绍了更改一个组件中的值会影响另一个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个angular 6应用程序,它有一个顶部栏和一个位于其下方的内容区域.这些是不同的组件,我目前正在开发用户个人资料页面.用户名也显示在顶部栏中.

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.

我的问题就像只要我在EditUser页面中更新了用户名一样,它就成功保存了,但是顶部栏上的用户名没有更新.在Vue.js中,我可以使用Vuex商店轻松地处理此问题.但是我该如何在Angular 6中处理呢?

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.

任何帮助将不胜感激.

推荐答案

您可以创建服务以在组件之间交换数据.可以是UserService提供对当前用户信息的访问.

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)
}

user-profile.component.ts

export class UserProfileComponent {

constructor(public userService: UserService) { }
}

user-profile.component.html

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

header.component.ts

export class HeaderComponent {

constructor(public userService: UserService) { }
}

header.component.html

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

因此,复杂的DI将创建一个单例UserService,并将相同的对象注入到两个组件中.而且,当您在其中任何一个位置进行更改时,更改都将显示在其他位置.

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.

这篇关于更改一个组件中的值会影响另一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆