1

I am working on an Angular +2 app where we provide the user an 'update your profile' page. The user is permitted to update their username from, say, "JSmith to "JDoe". We have a separate menu component in the upper right that displays some basic user data---username, email, etc.

Problem: After the user updates their username I want the save method to trigger updates to the menu component as well so that the displayed info--username,etc.--gets updated as well.

Question: what is the technique to execute changes to specific components?

3 Answers 3

2

If you want to notify other components of changes to data you can use a event model. Basically you create a singleton service that is injected into your components. This service has a Subject field which can be used to broadcast changes as well as subscribe to that broadcast.

userMenu.component.ts

import { Component, OnInit } from '@angular/core'; import { UserStateService } from './userState.service'; export class UserMenuComponent implements OnInit { constructor(private readonly userStateService: UserStateService) { } ngOnInit() { this.userStateService.userChanged .asObservable() .subcribe(userInfo => {/* do something */}); } } 

userInput.component.ts

import { Component, OnInit } from '@angular/core'; import { UserStateService } from './userState.service'; export class UserInputComponent { userData: any; constructor(private readonly userStateService: UserStateService) { } onSave() { this.userStateService.userChanged.next(this.userData); } } 

userState.service.ts

import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserStateService { userChanged = new Subject(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Igor. I appreciate the level of detail in your answer.
1

You need to have a service and exposing an Observable<UserInfo> then all of your components such as menu, toolbar and ... subscribing to this service to get UserInfo, then when a user info changes you only need to next that observable, everything will be updated automagically

Comments

0

You can create a service that has the username , email , etc properties as public static properties. So you can update the static variables in one component and read them in another and it will change instantly. (the 2 components will work on the same properties stored in the service , one component will change those properties and the other will be reading directly from them).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.