在Angular中,父组件的数据可以通过属性绑定或使用@Input装饰器传递给子组件。如果你无法获取父组件的数据,可能有以下几种解决方法:
子组件中,使用@Input装饰器声明一个属性来接收父组件传递的数据。 子组件代码:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
{{data}}
`
})
export class ChildComponent {
@Input() data: any;
}
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
public sharedData: any;
}
在父组件中,将数据存储在共享数据的服务中:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-parent',
template: `
`,
providers: [DataService]
})
export class ParentComponent {
constructor(private dataService: DataService) {}
sendDataToChild() {
this.dataService.sharedData = 'Hello from parent';
}
}
在子组件中,从共享数据的服务中获取数据:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-child',
template: `
{{data}}
`
})
export class ChildComponent {
constructor(private dataService: DataService) {}
get data() {
return this.dataService.sharedData;
}
}
以上是两种常见的解决父组件数据无法获取的方法,你可以根据自己的需求选择适合的方法来解决问题。