[英]How do you convert code from rxjs v5 to rxjs v6 for catch?
我正在跟隨thinkster.io的教程,內容涉及使用angular 2+編碼“與服務器交互和認證的服務”。 我在使用RXJS v5時陷入了這一節,無法將其轉換為新的RXJS v6以使代碼正常工作。
我正在處理以下文件格式,但出現錯誤:
user.service.ts
import { Observable } from 'rxjs'; import { BehaviorSubject } from 'rxjs'; import { ReplaySubject } from 'rxjs'; import { map, catch } from 'rxjs/operators'; @Injectable() export class UserService { private currentUserSubject = new BehaviorSubject<User>(new User()); public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged(); private isAuthenticatedSubject = new BehaviorSubject<boolean>(false); public isAuthenticated = this.isAuthenticatedSubject.asObservable(); attemptAuth(type, credentials): Observable<User> { let route = (type === 'login') ? '/login' : ''; return this.apiService.post('/users' + route, {user: credentials}) .map( data => { this.setAuth(data.user); return data; } ); } getCurrentUser(): User { return this.currentUserSubject.value; } }
api.service.ts:
import { Observable } from 'rxjs'; import { map, catch } from 'rxjs/operators'; private formatErrors(error: any) { return Observable.throw(error.json()); } get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> { return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params }) .catch(this.formatErrors) .map((res:Response) => res.json()); } put(path: string, body: Object = {}): Observable<any> { return this.http.put( `${environment.api_url}${path}`, JSON.stringify(body), { headers: this.setHeaders() } ) .catch(this.formatErrors) .map((res:Response) => res.json()); } post(path: string, body: Object = {}): Observable<any> { return this.http.post( `${environment.api_url}${path}`, JSON.stringify(body), { headers: this.setHeaders() } ) .catch(this.formatErrors) .map((res:Response) => res.json()); } delete(path): Observable<any> { return this.http.delete( `${environment.api_url}${path}`, { headers: this.setHeaders() } ) .catch(this.formatErrors) .map((res:Response) => res.json()); } }
運行代碼將給我以下錯誤:src / app / shared / services / api.service.ts(5,15)中的錯誤:錯誤TS1003:預期的標識符。
擺脫它的唯一方法是注釋掉以下代碼行public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();
。 但是代碼無法按照教程的預期運行。
根據遷移文檔,您需要做的只是將catch
更改為catchError
並利用新的管道語法。
請參見HowTo:轉換為管道語法 :
更改了以下運算符名稱,因為它們的點鏈名稱是JavaScript中的保留字:
do
->tap
catch
- >catchError
switch
-> switchAll
finally
->finalize
要將點鏈運算符轉換為可管道運算符,請從可觀察的源將所有運算符包裝在pipe()方法中,刪除點,然后添加逗號以將每個操作作為參數傳遞給pipe()。
例如,以下代碼使用鏈接:
source .map(x => x + x) .mergeMap(n => of(n + 1, n + 2) .filter(x => x % 1 == 0) .scan((acc, x) => acc + x, 0) ) .catch(err => of('error found')) .subscribe(printResult);
轉換為管道:
source.pipe( map(x => x + x), mergeMap(n => of(n + 1, n + 2).pipe( filter(x => x % 1 == 0), scan((acc, x) => acc + x, 0), )), catchError(err => of('error found')), ).subscribe(printResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.