tiêm phụ thuộc - Truy cập Dữ liệu/Thuộc tính của Thành phần Cha từ Thành phần Con trong Angular2
Tôi đang "không còn cách nào nữa" và hoàn toàn không biết phải làm gì. Tôi sắp khóc rồi!
Tôi đang cố gắng tự học Angular2 sau nhiều năm vui vẻ sử dụng AngularJS - Tôi có một ứng dụng Angular2 có thành phần cấp cao như được gọi là App
@Component({
selector: 'app', // <app></app>
providers: [...FORM_PROVIDERS],
directives: [...ROUTER_DIRECTIVES],
template: require('./app.html')
})
@RouteConfig([
{path: '/', component: Home, name: 'Home'},
{path: 'about', component: About, name: 'About'},
{path: 'profile', component: Profile, name: 'Profile'},
{path: 'profile/:id', component: ForeignProfile, name: 'ForeignProfile'}
])
export class App {
userStatus: UserStatus;
userOnlineContacts: UserContact[];
constructor(private userData: UserData) {
this.userStatus = new UserStatus();
}
ngOnInit() {
Observable.forkJoin([
this.userData.getUserStatus(),
this.userData.getContacts()
]).subscribe( (t) => {
this.userStatus = t[0];
this.userOnlineContacts = t[1].onlineContacts;
});
// Polling thing for this.userOnlineContacts...
this.userData.pollContacts().subscribe(
(data) => {
this.userOnlineContacts = data.onlineContacts;
});
}
}
Tôi trông như thế này trong index.html của tôi
<app>Loading...</app>
Hiện tại tôi đang sử dụng ng-router nên trong app.html của tôi tôi có các thẻ <router-outlet></router-outlet> được lồng vào HTML của tôi. Vì vậy các component con của tôi được chèn vào các thẻ này - tôi không bao giờ đặt các thẻ selector của mình vào HTML (vì vậy tôi giả sử rằng tôi không thể truyền dữ liệu bằng data-binding). Bên trong <router-outlet></router-outlet> tôi truy cập component con khi tôi điều hướng đến component ForeignProfile, mã của component con như sau...
@Component({
selector: 'foreign-profile',
template: require('app/components/foreign-profile/foreign-profile.html'),
providers: [],
directives: [],
pipes: []
})
export class ForeignProfile implements OnInit {
userProfile: any;
routeId: string;
userPhotos: any;
userInfo: any;
constructor(private userData: UserData, private routeParams: RouteParams) {
this.routeId = routeParams.get('id');
this.userProfile = {}; // not sure why I need to put this here otherwise we have 'undefined' error
}
ngOnInit() {
// Use forkJoin as we don't need order in the calls
Observable.forkJoin([
this.userData.getUserPhotos(this.routeId),
this.userData.getUserInfo(this.routeId),
this.userData.getUserBaseData(this.routeId)])
.subscribe(t => {
this.userPhotos = t[0];
this.userInfo = t[1];
this.userProfile = t[2];
// do more stuff here
});
}
}
Bên trong thành phần này, tôi muốn truy cập các thuộc tính của thành phần App, ví dụ this.userStatus & this.userOnlineContacts. Tôi không muốn tạo một service để thực hiện các cuộc gọi HTTP lặp đi lặp lại, tôi muốn tiêm trực tiếp các thuộc tính của cha vào con. Trong AngularJS, tôi có thể đã sử dụng thứ gì đó như $scope.$parent.userStatus. Bây giờ tôi đã xem xét việc tiêm thành phần cha (App) vào con (ForeignProfile) bằng cách sửa đổi thành phần:
đây là thành phần ForeignProfile
import {App} from '../../app'
@Component({
// blah blah...
})
export class ForeignProfile implements OnInit {
// code removed for example, easier to read
userStatus: any;
constructor(private userData: UserData, private routeParams: RouteParams, @Inject app:App) {
// code removed for example, easier to read
this.userStatus = app.userStatus;
}
Và sau đó với phụ huynh...
import {Injectable, Component} from 'angular2/core';
@Injectable()
@Component({
selector: 'app', // <app></app>
Điều này làm cho console của tôi phát điên. Có ai có thể giải thích chính xác cách tôi có thể truy cập các thuộc tính từ component App trong component ForeignProfile của tôi không? Tôi đã mất hàng giờ cho việc này rồi! Cảm ơn trước.
Câu trả lời #1
Như @Günter Zöchbauer đã đề cập chính xác, bạn phải sử dụng các khái niệm dịch vụ Angular để chia sẻ dữ liệu giữa các thành phần.
Trong trường hợp bạn vẫn muốn truy cập vào component App của mình, bạn có thể làm điều đó trong constructor của ForeignProfile như sau:
constructor(@Host() @Inject(forwardRef(() => App)) app: App)
{
}
