在Angular中,可以通过使用父组件的属性绑定将API响应传递给子组件。以下是一个使用属性绑定传递API响应给子组件的示例代码:
父组件HTML模板:
父组件TS文件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
apiResponse: any;
constructor(private apiService: ApiService) {
this.getApiResponse();
}
getApiResponse() {
this.apiService.getData().subscribe(response => {
this.apiResponse = response;
});
}
}
子组件TS文件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() apiResponse: any;
constructor() { }
}
在这个示例中,父组件通过apiResponse
属性将API响应传递给子组件。在子组件中,通过使用@Input()
装饰器将父组件传递的值绑定到apiResponse
属性上。这样子组件就能访问和使用API响应的数据了。