什么会触发错误:无法读取未定义的属性“subscribe”?
2021-05-24
263
我编写了一个 http 服务。
它包含一个函数 请求调用 :
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { ApiMethod, AuthEndPoints } from '../conts';
import { environment } from '../../../../environments/environment';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http: HttpClient) {
}
requestCall(method: ApiMethod, api: AuthEndPoints, data?: any): any {
let response;
switch (method) {
case ApiMethod.GET:
response = this.http.get(`${environment.baseUrl}${api}`).pipe(
catchError(err => this.handleError(err, this))
);
break;
case ApiMethod.POST:
response = this.http.post(`${environment.baseUrl}${api}`, data).pipe(
catchError(err => this.handleError(err, this))
);
break;
case ApiMethod.PUT:
response = this.http.put(`${environment.baseUrl}${api}`, data).pipe(
catchError(err => this.handleError(err, this))
);
break;
case ApiMethod.DELETE:
response = this.http.delete(`${environment.baseUrl}${api}`).pipe(
catchError(err => this.handleError(err, this))
);
break;
}
}
在我的登录组件中,我按如下方式调用此方法:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpService } from '../../core/services/http/http.service';
import { ApiMethod, AuthEndPoints } from '../../core/services/conts';
import { StorageService } from '../../core/services/storage/storage.service';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private http: HttpService,
private router: Router,
private storage: StorageService
) { }
login(loginForm: LoginForm): any {
this.http.requestCall(ApiMethod.POST, AuthEndPoints.LOGIN, loginForm).subscribe(res => {
this.storage.saveToken(res.auth_token);
this.router.navigate(['/dashboard']);
}, (error) => {console.log(error)})
}
当我登录时,我收到以下错误消息:
core.js:6456 ERROR TypeError: Cannot read property 'subscribe' of undefined
at AuthService.login (auth.service.ts:35)
at LoginComponent.onSubmit (login.component.ts:50)...
我不太明白是什么触发了这个错误。
我尝试了另一种没有 requestCall() 方法的方法,这个方法也有效。但我想用这种方法。
你怎么看?
1个回答
您没有从方法返回任何响应,因此只需返回变量:
requestCall(method: ApiMethod, api: AuthEndPoints, data?: any): any {
let response;
switch (method) {
case ApiMethod.GET:
response = this.http.get(`${environment.baseUrl}${api}`).pipe(
catchError(err => this.handleError(err, this))
);
break;
case ApiMethod.POST:
response = this.http.post(`${environment.baseUrl}${api}`, data).pipe(
catchError(err => this.handleError(err, this))
);
break;
case ApiMethod.PUT:
response = this.http.put(`${environment.baseUrl}${api}`, data).pipe(
catchError(err => this.handleError(err, this))
);
break;
case ApiMethod.DELETE:
response = this.http.delete(`${environment.baseUrl}${api}`).pipe(
catchError(err => this.handleError(err, this))
);
break;
return response; // <-- here
}
eko
2021-05-24