带有Observable的Angular5 handleErrors:错误Observable.throw不是函数

时间:2018-06-19 17:47:07

标签: angular typescript rxjs

您能帮我解决此错误吗?

core.js:1542错误TypeError:rxjs__WEBPACK_IMPORTED_MODULE_3 __。Observable.throw不是函数

Angular CLI:6.0.8 / rxjs 6.2.1

import { Injectable } from '@angular/core';
import { User } from './../classes/user';
import { AppSettings } from './appSettings';
import { HttpClient,HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
      providedIn: 'root'
})

export class LoginService {

      constructor(private http: HttpClient){ }

      login(user:User): Observable<User> {                               
            return this.http.post<User>(AppSettings.BASE_URL + "/login",user)
            .pipe(catchError(this.handleServerError));   
      }

      handleServerError(error: any  | any) {
            console.log(error.error || error.json() || error);
            return Observable.throw(error.error || error.json() || error || 'Server error');  <<< ERROR
      }

}

1 个答案:

答案 0 :(得分:2)

我已经解决了:

app.module.ts

 import {HttpClientModule} from '@angular/common/http';
 .
 .
 . 
 imports: [
    BrowserModule,
    HttpClientModule
  ]

service / login.ts

import { Injectable } from '@angular/core';
import { User } from './../classes/user';
import { AppSettings } from './appSettings';
import { HttpClient,HttpHeaders, HttpParams } from '@angular/common/http';
import {  throwError } from 'rxjs';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
import { catchError, retry } from 'rxjs/operators';

const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'my-auth-token'
      })}


@Injectable({
      providedIn: 'root'
})

export class LoginService {

      constructor(private http: HttpClient){

      }

      login(user:User): Observable<User> {                               
            return this.http.post<User>(AppSettings.BASE_URL + "/login",user)
            .pipe(catchError(this.handleServerError));   
      }

      handleServerError(error: any | any ) {
            console.log(error.error || error.json() || error);
            return throwError(error.error || error.json() || error || 'Server error');
      }

}

login.component.ts

 import { LoginService } from '../../services/login';

this.loginService.login(new User("admin","admin")).subscribe(                  
                  user => {
                        //to do ; 
                  },
                  error => {                                                  
                         throw error;
                  }                  
  );