我有以下模块路由设置
const personsRoutes: Routes = [
{
path: '',
redirectTo: '/persons',
pathMatch: 'full'
},
{
path: 'persons',
component: PersonsComponent,
children: [
{
path: '',
component: PersonListComponent
},
{
path: ':id',
component: PersonDetailComponent,
children: [
{
path: '',
redirectTo: 'info',
pathMatch: 'full'
},
{
path: 'info',
component: PersonDetailInfoComponent,
},
{
path: 'edit',
component: PersonDetailEditComponent,
},
{
path: 'cashflow',
component: PersonDetailCashflowComponent,
}
]
}
]
}
];
因此,当我尝试打开http://localhost:4200/persons/3/edit
时,Angular2将首先加载PersonsComponent,然后加载PersonDetailComponent,然后加载PersonDetailInfoComponent。
现在在PersonDetailComponent中我有一个服务请求来从后端检索人员信息,我也想在PersonDetailInfoComponent中使用检索到的Person信息。
所以我的问题是Angular2是否提供了一种内置方式,我可以从父组件访问变量(例如:在PersonDetailInfoComponent中访问PersonDetailComponent.personModelfrom)。
是否有一个Angular-endorsed" right"这样做的方式还是每个人最终都会实现自己的自定义解决方案的事情之一?此外,如果没有现成的,有没有计划在Angular2的更高版本中提供此功能?
欢呼并提前感谢。
P.S。
我的依赖项/版本如下:
"@angular/common": "2.0.0",
"@angular/compiler": "2.0.0",
"@angular/core": "2.0.0",
"@angular/forms": "2.0.0",
"@angular/http": "2.0.0",
"@angular/platform-browser": "2.0.0",
"@angular/platform-browser-dynamic": "2.0.0",
"@angular/router": "3.0.0",
"core-js": "^2.4.1",
"rxjs": "5.0.0-beta.12",
"ts-helpers": "^1.1.1",
"zone.js": "^0.6.23"
答案 0 :(得分:0)
好的,所以在没有人回复之后,在我浏览了文档和API后发现没有什么是我最终做的事情:
创建数据服务
import { Injectable } from '@angular/core';
import { PersonModel } from '../models/person/person.model';
@Injectable()
export class DataService {
private _person: PersonModel;
get person(): PersonModel {
return this._person;
}
set person(person: PersonModel) {
this._person = person;
}
constructor() { }
}
然后在我的父路由组件(PersonDetailComponent)中添加DataService
的提供程序,我将其注入构造函数并在每次从服务获取最新的person对象时更新dataservice.person对象。
@Component({
selector: 'person-detail',
templateUrl: './person-detail.component.html',
styleUrls: ['./person-detail.component.scss'],
providers: [DataService]
})
export class PersonDetailComponent implements OnInit {
private _sub: Subscription;
public _person: PersonModel;
constructor(private _route: ActivatedRoute, private _router: Router, private _service: PersonService, private _ds: DataService) { }
ngOnInit() {
console.log("Loaded person detail component");
this._sub = this._route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
this._service.get(id).subscribe(person => {
console.log(`Loaded person`, person);
this._person = person;
this._ds.person = person;
});
});
}
}
然后在我的子路由组件(PersonDetailEditComponent)中,我注入了数据服务,我只是从那里得到那个人。
@Component({
selector: 'person-detail-edit',
templateUrl: './person-detail-edit.component.html',
styleUrls: ['./person-detail-edit.component.scss']
})
export class PersonDetailEditComponent implements OnInit {
constructor(private _ds: DataService) { }
ngOnInit() {
console.log('Loaded person-edit view for', this._ds.person);
}
}
当然,对于主题/观察者/订阅者来说,数据服务可以更加清晰,但我只想分享一般方法。
希望这可以帮助有人在路上。