Angular 如何为HTTP调用编写通用服务并在模块文件中使用其响应/错误

Angular 如何为HTTP调用编写通用服务并在模块文件中使用其响应/错误,angular,Angular,我是个新手,我想知道如何编写一个返回 结果/错误返回到模块文件 下面是我编写的一个身份验证服务函数: login(username: string, password: string) { const body = new HttpParams() .set('email', username) .set('password', password); return this.http.post('http://192.168.31.73:8080/ista

我是个新手,我想知道如何编写一个返回 结果/错误返回到模块文件

下面是我编写的一个身份验证服务函数:

login(username: string, password: string) {
    const body = new HttpParams()
      .set('email', username)
      .set('password', password);
    return this.http.post('http://192.168.31.73:8080/istar/rest/auth/login', body, {
      headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')

    })
      // See below - subscribe() is still necessary when using post().
      .subscribe(
      data => {
        console.log(data)
        localStorage.setItem('currentUser', JSON.stringify(data));

      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      }

      );
  }
当前url是静态的,我想在动态中创建,这样无论我传递什么url和参数,它都会使http调用返回响应

下面是进行此服务调用的组件文件逻辑:

const fetchdata = this.auth.login(this.form.get('email').value, this.form.get('password').value)

但我不知道如何从fetch data变量中获取结果。它的类型是subscriber。

您需要订阅每个http调用以从api获取所需的数据,因为默认情况下,所有其余调用都是冷调用,您需要订阅它以返回数据流

您最终可以编写一个通用函数来订阅,但我不认为为每个调用编写
。subscribe
有什么不同,而且您将来还需要一些自定义接口来生成模型数据,这些数据将在组件中处理,如

   this._service.getObservable().subscribe(res => {
      //data from service
    });
对于一般错误处理,您可以查看

从'rxjs'导入{Observable};
从“@angular/core”导入{Injectable};
从'@angular/common/http'导入{HttpEvent,HttpInterceptor,HttpHandler,HttpRequest};
从“@angular/common/http”导入{HttpErrorResponse};
@可注射()
导出类AngularInterceptor实现HttpInterceptor{
截取(req:HttpRequest,next:HttpHandler):可观察{
返回next.handle(req.do)(事件=>{},错误=>{
if(HttpErrorResponse的错误实例){
log(“被拦截器捕获的错误”);
//可观察的。投掷(错误);
}
});
}
}

不要订阅该服务。订阅是调用方组件的工作。如果成功,您可以使用将当前用户存储在本地存储中,并且仍然返回可观察的。
import { Observable } from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
        }
    });
  }
}