我有一个名为 home 的路由,它有三个子路由、文档、邮件和垃圾。在主路由组件中,它有一个名为“user”的变量。我知道有几种方法可以在父组件和子组件之间传递信息突出显示 here ,但我应该如何在父/子路由之间传递信息。
{ path: 'home', component: HomeComponent, children: [
{ path: 'documents', component: DocumentsComponent },
{ path: 'mail', component: MailComponent },
{ path: 'trash', component: TrashComponent },
]
},
服务
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 ;
}
}
组件
constructor(public router: Router, public http: Http, private homeService: HomeService) {
}
isLogged(){
return this.homeService.isLogged();
}
模板
<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>
最佳答案
您可以使用公共(public)服务来传递数据,如 Angular Documentation 中所述
基本上,您可以创建一个具有用户对象的服务,一旦您的父路由加载或对父组件执行某些操作,该对象就可以更新。
用户服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class UserService {
// Observable user
user = new Subject<string>();
}
然后当子路由组件被加载时,您可以从服务中检索值。
主页组件
@Component({
...
})
export class HomeComponent{
...
constructor(private userService:UserService ){}
someMethod = () =>{
this.userService.user.next(<pass user object>);
}
}
邮件组件
@Component({
...
})
export class HomeComponent{
...
constructor(private userService:UserService ){
this.userService.user.subscribe(userChanged);
}
userChanged = (user) => {
// Do stuff with user
}
}
如果您在父级中添加提供者,则服务对象在子级中将是相同的实例。
关于javascript - angular2 - 从父路由到子路由的传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38733519/