我在尝试使用来自父组件的 Observable 的数据渲染子组件时遇到问题,然后使用
async pipe
将数据转换为列表对象并使用 *NgFor 渲染它。我做到了:
在父组件中生成可观察数据:
// Parent Component
dataSet$!: Observable<Data[]>;
ngOnInit() {
this.dataSet$ = this.serviceData.getData();
}
使用异步管道将数据从父级发送到子级:
<!-- Parent Component Template -->
<ng-container *ngIf="dataSet$ | async as dataSet">
<app-row-data-list *ngFor="let data of dataSet" [data]="data"></app-row-data-list>
</ng-container>
带有@Input属性的子组件:
// Child Component
export class RowDataListComponent {
@Input() data!: Data;
}
但是,数据并未按预期呈现。子组件不会出现。
到目前为止我尝试的是以下答案中提到的修复:
但是我无法使用这些来修复它。我也找了很多。 实际上,我在这方面花了几个小时,所以如果有人可以帮助我的话。
非常感谢。
我不确定你的确切代码是什么,但在这里你可以看到一个工作示例:
interface Item {
userId: number;
id: number;
title: string;
completed: boolean;
}
type Items = Item[];
@Injectable({ providedIn: 'root' })
class DataService {
private http = inject(HttpClient);
getData() {
return this.http.get<Items>(`https://jsonplaceholder.typicode.com/todos`);
}
}
@Component({
selector: 'app-child',
standalone: true,
template: `
<pre>{{item() | json}}</pre>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [JsonPipe],
})
export class ChildComponent {
item = input<Item>();
}
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1>Hello from {{ name }}!</h1>
<app-child *ngFor="let data of (data$ | async)" [item]="data"></app-child>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ChildComponent, NgFor, AsyncPipe],
})
export class App {
name = 'Angular';
private dataService = inject(DataService);
data$ = this.dataService.getData().pipe(startWith([]), share());
}
bootstrapApplication(App, { providers: [provideHttpClient()] });