【发布时间】:2020-04-01 18:56:41
【问题描述】:
我有一个简单的结构,有多个组件和一个服务 [StackBlitz]:
服务
@Injectable()
export class Service {
constructor(private http: HttpClient) {}
post(entity: IEntity): Observable<IEntity> {
return this.http
.post<IEntity>('/api/entity', entity)
.pipe(map(parseDates));
}
get(): Observable<IEntity[]> {
return this.http
.get<IEntity[]>('/api/entity')
.pipe(map(parseDates));
}
}
组件0
@Component({
selector: 'app-component0',
template: `<app-component1></app-component1>
<app-component2></app-component2>`,
styleUrls: []
})
export class Component0 {}
组件1
@Component({
selector: 'app-component1-create',
template: `<button (click)="submit()">Submit</button>`,
styleUrls: []
})
export class Component1 {
constructor(private service: Service) { }
submit() {
this.service.post({foo: 'bar'})
.subscribe(console.info, console.error)
}
}
组件2
@Component({
selector: 'app-component2-table',
template: `<pre>{{ entities | json }}</pre>`,
styleUrls: []
})
export class Component2 implements OnInit {
entities: IEntity[];
constructor(private service: Service) { }
ngOnInit() {
this.service.get()
.subscribe(entities => this.entities = entities,
console.error)
}
}
如何让Component1 通过Service 更新Component2?
【问题讨论】:
-
您希望这样,每当您在
comp1上提交时(也就是说,向与comp2的entities属性无关的数据库发送post请求)它应该更新@comp2上的 987654337@,对吗? -
刚刚添加了一个StackBlitz 链接。对,那是正确的。可能是我不打算拥有
comp2的entities属性,可能是我在服务中存储了一些东西,可能是我使用BehaviourSubject或Subject而不是松散的大批。如何以可维护的方式处理这种常见情况?
标签: angular typescript rxjs angular-services angular-components