[英]angular2 - Pass value from parent route to child route
I have a route called home and it has three child routes, documents, mail and trash.我有一条名为 home 的路由,它包含三个子路由、文档、邮件和垃圾。 In the home route component it has a variable called 'user'.
在 home 路由组件中,它有一个名为“user”的变量。 I know there are a few ways of passing info between parent and child components highlighted here , but how am I suppose to pass info between parent/child routes.
我知道有几种方法可以在此处突出显示的父组件和子组件之间传递信息,但是我应该如何在父/子路由之间传递信息。
{ path: 'home', component: HomeComponent, children: [
{ path: 'documents', component: DocumentsComponent },
{ path: 'mail', component: MailComponent },
{ path: 'trash', component: TrashComponent },
]
},
Service服务
import { Injectable } from '@angular/core';
@Injectable()
export class HomeService {
// Mock user, for testing
myUser = {name:"John", loggedIn:true};
// Is Super Admin
isLogged():boolean {
if(this.myUser.role == true){
return true ;
}
return false ;
}
}
Component组件
constructor(public router: Router, public http: Http, private homeService: HomeService) {
}
isLogged(){
return this.homeService.isLogged();
}
Template模板
<div class="side-nav fixed" >
<li style="list-style: none">
<img alt="avatar" class="circle valign profile-image" height="64" src=
"../images/avatar.jpg" width="64">
<div class="right profile-name">
<!-- Value not changing even with service -->
{{myUser.role}}
</div>
</li>
You may use a common service to pass data like explained in the Angular Documentation您可以使用公共服务来传递数据,如Angular 文档中所述
Basically you may create a Service which will have a user object, which can be updated once your parent route gets loaded or with some action on parent component.基本上,您可以创建一个具有用户对象的服务,一旦您的父路由被加载或对父组件执行某些操作,就可以更新该服务。
UserService用户服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class UserService {
// Observable user
user = new Subject<string>();
}
And then when the child route component gets loaded you may retrieve the value from the Service.然后当子路由组件被加载时,您可以从服务中检索值。
HomeComponent主页组件
@Component({
...
})
export class HomeComponent{
...
constructor(private userService:UserService ){}
someMethod = () =>{
this.userService.user.next(<pass user object>);
}
}
MailComponent邮件组件
@Component({
...
})
export class HomeComponent{
...
constructor(private userService:UserService ){
this.userService.user.subscribe(userChanged);
}
userChanged = (user) => {
// Do stuff with user
}
}
Service object will be same instance in child if you add the provider in the parent.如果您在父级中添加提供者,服务对象将是子级中的相同实例。
Check out :- https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array查看:- https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
You can pass data while changing routes on click as :-您可以在单击更改路线时传递数据:-
<a [routerLink]="['/crisis-center', { foo: myVar }]">Crisis Center</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.