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

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

问题描述

我有一个 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>

因此,anggular 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天全站免登陆