我在返回可观察值时遇到问题。看来 mergeMap 内的代码根本没有运行。
代码:
book.service.ts
import {HttpClient, HttpHeaders} from '@angular/common/http';
export class bookService {
constructor(
private http: HttpClient,
...others
) {}
addNewBook(book): Observable<Book>{
##### Tried to use mergeMap otherwise the return type won't match
return this.tokenService.getToken().mergeMap((token: string) => {
console.log("Fire this...") <===== This is never output.
const myUrl = "www.testurl.com";
const parameters = {
bookTitle: book.name,
};
return this.http.post<Book>(myUrl, book);
})
}
token .service.ts
public token$: Subject<string>;
..others
public getToken(): Observable<string> {
return this.token$; <= return Observable<string> not Observable<Book>
}
book.component.ts 调用 addNewBook 方法。
...others
return Promise.resolve()
.then(() => {
return bookService.addNewBook(book);
}).then((result) => {
console.log(result);
})
我无法真正更改 token 服务,因为它已在其他地方使用,我不确定为什么 mergeMap 内的代码未运行。有人可以帮我吗?非常感谢!
最佳答案
除非您订阅 bookService.addNewBook(book)
的结果,否则它不会起作用。仅从 then
回调返回它不会订阅。您至少需要添加 toPromise
。
...others
return Promise.resolve()
.then(() => {
return bookService.addNewBook(book).toPromise();
}).then((result) => {
console.log(result);
})
关于javascript - (Angular)在我的情况下如何返回不同的 Observable 类型请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50914562/