在通用方法上使用 headers 时需要创建自定义 Observable
Create custom Observable is needed when use headers on generic method
我已经创建了一个通用服务。
common.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor(private http: HttpClient) { }
post(url: string, params: any): Observable<any> {
return new Observable(observer => {
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) };
this.http.post(url, params, httpOptions)
.subscribe(response => {
observer.next(response);
observer.complete();
}, (err) => {
observer.error(err);
});
});
}
}
my-service.ts
book(data: Spa): Observable<any> {
return this.commonService.post(`${environment.apiURL}/my/v3/my.json`, data);
}
page.ts
book() {
this.myService.book(spa).subscribe((res: any) => {
}, error => { console.log(error); });
}
}
问: 我需要在 post()
方法上创建自定义 Observable
吗?由于 this.http.post(url, params, httpOptions)
returns Observable
希望我不需要再创建自定义 Observable
否(即 common.ts
)?
注意:以上工作正常,没有错误。
函数 post returns 是一个可观察对象,如果需要,可以输入它,然后您不需要创建另一个可观察对象,您可以简化为:
post(url: string, params: any): Observable<any> {
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) };
return this.http.post(url, params, httpOptions);
}
我已经创建了一个通用服务。
common.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor(private http: HttpClient) { }
post(url: string, params: any): Observable<any> {
return new Observable(observer => {
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) };
this.http.post(url, params, httpOptions)
.subscribe(response => {
observer.next(response);
observer.complete();
}, (err) => {
observer.error(err);
});
});
}
}
my-service.ts
book(data: Spa): Observable<any> {
return this.commonService.post(`${environment.apiURL}/my/v3/my.json`, data);
}
page.ts
book() {
this.myService.book(spa).subscribe((res: any) => {
}, error => { console.log(error); });
}
}
问: 我需要在 post()
方法上创建自定义 Observable
吗?由于 this.http.post(url, params, httpOptions)
returns Observable
希望我不需要再创建自定义 Observable
否(即 common.ts
)?
注意:以上工作正常,没有错误。
函数 post returns 是一个可观察对象,如果需要,可以输入它,然后您不需要创建另一个可观察对象,您可以简化为:
post(url: string, params: any): Observable<any> {
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) };
return this.http.post(url, params, httpOptions);
}