我有一个组件,我通过像这样调用customer
来添加一个名为api
的新对象:
public onAdd(): void {
this.myCustomer = this.customerForm.value;
this.myService.addCustomer(this.myCustome).subscribe(
() => { // If POST is success
this.callSuccessMethod();
},
(error) => { // If POST is failed
this.callFailureMethod();
},
);
}
服务文件:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {ICustomer } from 'src/app/models/app.models';
@Injectable({
providedIn: 'root',
})
export class MyService {
private baseUrl : string = '....URL....';
constructor(private http: HttpClient) {}
public addCustomer(customer: ICustomer): Observable<object> {
const apiUrl: string = `${this.baseUrl}/customers`;
return this.http.post(apiUrl, customer);
}
}
如组件代码所示,我已经预订了api
呼叫,如下所示:
this.myService.addCustomer(this.myCustome).subscribe(
() => { // If POST is success
.....
},
(error) => { // If POST is failed
...
},
);
但是,我想将结果订阅到另一个组件中,我已经这样尝试过:
public getAddedCustomer() {
this.myService.addCustomer().subscribe(
(data:ICustomer) => {
this.addedCustomer.id = data.id; <======
}
);
}
我收到以下错误消息:Expected 1 arguments, but got 0
,因为我没有通过任何parameter
。
在其他组件中订阅api调用的正确方法是什么? POST 操作之后。
因为我想获取其他功能的添加对象ID。
答案 0 :(得分:0)
完全取决于应用程序的设计以及组件之间的关系。您可以使用“主题”将数据多播到多个订阅者。
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { ICustomer } from 'src/app/models/app.models';
@Injectable({
providedIn: 'root',
})
export class MyService {
private baseUrl : string = '....URL....';
private latestAddedCustomer = new Subject();
public latestAddedCustomer$ = this.latestAddedCustomer.asObservable()
constructor(private http: HttpClient) {}
public addCustomer(customer: ICustomer): Observable<object> {
const apiUrl: string = `${this.baseUrl}/customers`;
return this.http.post(apiUrl, customer).pipe(map((data) => this.latestAddedCustomer.next(data)));
}
}
并订阅以下主题
this.latestAddedCustomer$.subscribe()
应该为您提供最新添加的客户详细信息。即使我不会这样做。我基本上会编写一个单独的服务来在组件之间共享数据,或者如果它在整个应用程序中使用,则会编写一个缓存服务。但是这里的想法是使用主题的概念。您可以详细了解Here