我最近将代码库从Angular 4更新到了Angular6。这样做的一部分是将所有rxjs函数移到可管道运算符中。
我想知道我的语法是否做错了,因为在语法更新后我之前发出的patch
请求不再起作用。
这是我在Angular 4中工作的代码:
csrfToken() {
const url = `path/to/csrf-token`;
const options = new RequestOptions({
withCredentials: true,
});
return this.http
.get(url, options)
.map((res: Response) => {
return res.text();
})
.map((token: string) => {
if (!token) {
throw new Error(
'Successfully requested a CSRF token but the response was empty.'
);
}
return token;
});
}
writeFavorites(favorites: any[]) {
const url = `path/to/favorites`;
// writing favorites requires CSRF Token
return this.csrfToken().flatMap(token => {
const opts = new RequestOptions({
headers: new Headers({
'MY-TOKEN': token,
'Content-Type': 'application/json',
}),
withCredentials: true,
});
return (
this.http
.patch(url, JSON.stringify(favorites), opts)
// PATH currently just replies with 200 and empty body
.map((res: Response) => {
return null;
})
);
});
}
这是更新到Angular 6之后的代码。
csrfToken(): Observable<string> {
const url = `path/to/csrf-token`;
const options = {
withCredentials: true,
};
return this.http.get<string>(url, options).pipe(
map((res: Response) => {
return res.text();
}),
map((token: string) => {
if (!token) {
throw new Error('Successfully requested a CSRF token but the response was empty.');
}
return token;
})
);
}
writeFavorites(favorites: any[]) {
const url = `path/to/favorites`;
// writing favorites requires CSRF Token
return this.csrfToken().pipe(
flatMap(token => {
const opts = {
headers: new HttpHeaders({
'MY-TOKEN': token,
'Content-Type': 'application/json',
}),
withCredentials: true,
};
return (
this.http
.patch(url, JSON.stringify(favorites), opts)
// PATH currently just replies with 200 and empty body
.pipe(
map((res: Response) => {
// in Angular 7 the typescript compiler
// rejects this assignment
// see comment below
return null;
})
)
);
})
);
}
// Angular 7 - TypeScript compile error:
// Argument of type 'OperatorFunction<Response, Promise<string>>'
// is not assignable to parameter of type 'OperatorFunction<string, Promise<string>>'.
// Type 'Response' is not assignable to type 'string'.
我的问题:为什么更新后没有提出patch
请求?
如果更新正确,那么我猜问题出在其他地方,但是我想确定一下,因为我也是RXJS的新手,所以也许我的语法是错误的。
谢谢。
答案 0 :(得分:-2)
如果Angular 6中存在语法错误 和rxjs V6 +,只需安装rxjs-compat
npm i rxjs-compat