【发布时间】:2019-04-05 09:11:09
【问题描述】:
我有一个组件,我通过像这样调用api 添加一个名为customer 的新对象:
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; <======
}
);
}
我收到这个 lint 错误:Expected 1 arguments, but got 0,因为我没有传递任何 parameter。
在其他组件中订阅 api 调用的正确方法是什么? POST 操作后。
因为我想为其他功能添加对象 ID。
【问题讨论】:
-
这个“另一个组件”与组件有什么关系?有没有父子关系?
-
没有父子关系
-
我想在
same component或其他component中获取added object ID。
标签: javascript angular typescript angular6