[英]Angular: Passing data or events from child to parent with router-outlet
I have parent AppComponent with routes login, home etc. When user logs in with creds, I'm saving the user creds in Sessionstorage. 我有父AppComponent与路由登录,家庭等。当用户使用creds登录时,我在Sessionstorage中保存用户信用。 When the login is successful I want to display some part of the data in header of AppComponent.html, so I have to getItems from seesionstorage.
登录成功后,我想在AppComponent.html的标题中显示部分数据,所以我必须从seesionstorage中获取getItems。 How do I trigger the event to notify AppComponent from LoginComponent?
如何触发事件以从LoginComponent通知AppComponent? I'm using router-outlet so I cannot use EventEmitter.
我正在使用路由器插座,所以我不能使用EventEmitter。 I can use BehaviourSubject but there is no valid method in AppComponent to call.
我可以使用BehaviourSubject,但AppComponent中没有有效的方法可以调用。 Please suggest.
请建议。
Use communication service for this: 使用通信服务:
CommunicationService.ts CommunicationService.ts
@Injectable()
export class CommunicationService {
constructor() { }
private emitChangeSource = new Subject<any>();
changeEmitted$ = this.emitChangeSource.asObservable();
emitChange() {
this.emitChangeSource.next();
}
}
login.ts: login.ts:
constructor(
private communicationService: CommunicationService
) {
}
login(){
this.communicationService.emitChange()
}
AppComponent.ts: AppComponent.ts:
constructor(
private communicationService: CommunicationService,
) {
communicationService.changeEmitted$.subscribe(data => {
// here fetch data from the session storage
})
}
Hope this helps. 希望这可以帮助。
am just expanding 'Hrishikesh Kale' answer a bit, from your view, you are storing user credentials in localstorage. 我只是扩展'Hrishikesh Kale'的答案,从您的角度来看,您将用户凭据存储在localstorage中。
just get that stored data in service 只是将存储的数据投入使用
credentials(){
const usercredential = localStorage.getItem('usercredential')
if(usercredential === "undefined"){
return false
}
else {
return true
}
}
and in your html 并在你的HTML中
<a *ngIf="service.loggedIn() && service.credentials()">Admin</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.