Angular7:如何使用服务代替@Input?
Angular 7: How to use a service instead of @Input?
到处都说您可以通过@input 或服务将数据从parent 传递到child。我们有一个始终使用服务的策略,但在这种特殊情况下,我只知道如何使用@Input 来实现它。此代码完全符合我的意图:
Parent - component.html
<ul>
<li *ngFor="let item of items">
<app-item [item]="item"></app-item>
</li>
</ul>
Child (app-item) - component.ts
@Input() item: Item = {price: 0; size: 0; color: 'none'};
如何更改 child,以便数据改为来自服务?我知道如何做到这一点 'onClick',但不知道如何在 parent 上不涉及用户操作时如何做到这一点,只是列表的裸露显示(出于其他原因,parent 和child 必须是单独的组件)。
如果在 parent 的每次迭代中,我可以想象这是可行的唯一方法(但这是一个糟糕的想法),我会做类似 subject.next(item) 的事情。
任何想法都会非常有用,我完全不知道我应该做什么。
编辑:
弄清楚问题后,你最好的选择是@Input()
装饰器。数据来自 API 并且每个组件都会发生变化,因此,使用服务不是一个好主意。用你现有的去说服你的主管。
创建服务:
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable()
export class MyService {
item = new BehaviorSubject<any>(null);
constructor() {
}
}
将上述服务导入 Parent 和 Child 组件。 parent 组件更新值,child 组件观察它。
在 parent 需要更新的地方:
this.myService.item.next('Pass this data to the child');
并在child订阅它:
this.myService.item.subscribe(data => this.data = data);
在 parent 和 child 组件中:
constructor(private myService: MyService) {}
并确保在 ngOnDestroy()
中退订。
到处都说您可以通过@input 或服务将数据从parent 传递到child。我们有一个始终使用服务的策略,但在这种特殊情况下,我只知道如何使用@Input 来实现它。此代码完全符合我的意图:
Parent - component.html
<ul>
<li *ngFor="let item of items">
<app-item [item]="item"></app-item>
</li>
</ul>
Child (app-item) - component.ts
@Input() item: Item = {price: 0; size: 0; color: 'none'};
如何更改 child,以便数据改为来自服务?我知道如何做到这一点 'onClick',但不知道如何在 parent 上不涉及用户操作时如何做到这一点,只是列表的裸露显示(出于其他原因,parent 和child 必须是单独的组件)。
如果在 parent 的每次迭代中,我可以想象这是可行的唯一方法(但这是一个糟糕的想法),我会做类似 subject.next(item) 的事情。 任何想法都会非常有用,我完全不知道我应该做什么。
编辑:
弄清楚问题后,你最好的选择是@Input()
装饰器。数据来自 API 并且每个组件都会发生变化,因此,使用服务不是一个好主意。用你现有的去说服你的主管。
创建服务:
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable()
export class MyService {
item = new BehaviorSubject<any>(null);
constructor() {
}
}
将上述服务导入 Parent 和 Child 组件。 parent 组件更新值,child 组件观察它。
在 parent 需要更新的地方:
this.myService.item.next('Pass this data to the child');
并在child订阅它:
this.myService.item.subscribe(data => this.data = data);
在 parent 和 child 组件中:
constructor(private myService: MyService) {}
并确保在 ngOnDestroy()
中退订。