我正在尝试将多个角度组件订阅到单个http服务。他的事件流程是:用户点击test-data.component.html>中的按钮; test-data.service发出POST请求> test-data.component中的订阅接收数据AND parent.component.ts接收数据。问题是parent.component.ts永远不会从POST收到新数据。我是否需要通知parent.component服务提供商发生了哪些变化?以下是该应用程序的相关部分:
parent.component.html
<div>
<app-test-data></app-test-data>
</div>
parent.component.ts
@Component({
selector: 'app-short-form',
templateUrl: './short-form.component.html',
styleUrls: ['./short-form.scss'],
providers:[ShortFormService, TestDataService]
})
constructor(
private testDataService: TestDataService,
) { }
ngOnInit() {
this.testDataService.getTestData()
.subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
console.log(' Done!', event.body);
}
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {
console.log("Server-side error occured.");
}
}
)
}
测试data.component.html
<button m(click)="getTestData($event)" >Populate w/ match</button>
测试data.component.ts
@Component({
selector: 'app-test-data',
templateUrl: './test-data.component.html',
styleUrls: ['./test-data.component.scss'],
providers: [TestDataService]
})
constructor(
private testDataService: TestDataService,
) { }
getTestData(event){
event.preventDefault();
this.testDataService.getTestData()
.subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
console.log(' Done!', event.body);
}
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {`enter code here`
console.log("Server-side error occured.");
}
}
)
}
测试data.service.ts
constructor(
private http:HttpClient
) { }
getTestData(): Observable<HttpEvent<any>> {
const req = new HttpRequest('POST', this.testDataUrl, {
reportProgress: true,
});
var result = this.http.request(req).share();
return result
答案 0 :(得分:1)
您应该使用Subject或BehaviourSubject并让您的compometes订阅它。 您可以在此链接中找到有关这些主题的更多信息: http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject