处理http方法的常用代码,如get,put,post,delete

时间:2018-02-20 17:18:51

标签: angular http-method

使用angularjs or angular-1,我曾经使用公共代码(不完全)来处理http methods like GET, PUT, POST, DELETE

// can be called with GET, PUT, POST, DELETE

sharedService.process(method, url, data, headers).then(function(result){

     //handle response here
     .....

})

sharedservice.js

// this would handle all types of requests. eg. GET, PUT, POST, DELETE

process: function (method, url, data, header){
  ...
  ...
  return $http({
          method  : method,
          url     : url,
          headers : headers,
          data    : data
   })
  ...
  ...
}

如何以角度2/4/5实现相同的目标? 有没有办法通过promiseobservable响应来实现它? 是否有任何常用的方法来处理HTTP方法?

1 个答案:

答案 0 :(得分:0)

您可以使用httpClient拦截器:

文档链接为:Angular io

为每个请求设置身份验证标头的示例:

 import { Injectable } from '@angular/core';
 import {
   HttpRequest,
   HttpHandler,
   HttpEvent,
   HttpInterceptor
 } from '@angular/common/http';
 import { AuthService } from './auth/auth.service';
 import { Observable } from 'rxjs/Observable';

 @Injectable()
 export class TokenInterceptor implements HttpInterceptor {

 constructor(public auth: AuthService) {}

 intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {

    request = request.clone({
       setHeaders: {
         Authorization: `Bearer ${this.auth.getToken()}`
       }
    });

    return next.handle(request);
 }
}

编辑:

在我正确指出你的观点后,你应该做的是:

编写登录服务:

 import {Injectable} from '@angular/core';
 import { HttpClient} from '@angular/common/http';
 import {Observable} from 'rxjs/Observable';


 @Injectable()
 export class AuthenticationService{

      constructor(private http:HttpClient){}

      public isUserNameExist(username:string):Observable<boolean>{
            private url:string = "Your server side url";
            return this.http.get(url);
      }

      public login(username:string, password:string)Observable<User>{
             private url:string = "";
             return this.http.post<User>(url);
      }

 }

在您的组件中,您可以编写以下内容:

 export class loginComponent{

    constructor(private authService:AuthenticationService){}


    onFromSubmit(username:string, password:string){
        this.authService.login(username, password)
            .subscribe(user => //Do what ever you want);
    } 
 }