ng2 http

http API

HTTP 请求是可以通过 unsubscribe() 方法来取消的。

在app.module中导入HttpClientModule

 import { HttpClientModule } from "@angular/common/http";

 imports: [ HttpClientModule ],

组件中注入

import { HttpClient } from "@angular/common/http";

constructor(private http: HttpClient) {}

get post

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { stringify } from 'querystring';

  postData() {
    const headers = new HttpHeaders()
      .append('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

     const body = stringify({ name: "post-json" });
      
    this.http.post('http://localhost:3000/post', body , {
      params: { test: 'pppppp' }, // query
      headers: headers, // 头信息
      responseType: 'json', // 后台返回的数据类型
    }).subscribe(res => {
      console.log(res);
    })
  }

http请求拦截器

noop-interceptor.ts

import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from "@angular/common/http";

import { Observable } from "rxjs";
import { tap } from "rxjs/operators";

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    let secureReq;
    if (req.method === "GET") {
      const newParams = req.params.set("token", "233");
      secureReq = req.clone({params: newParams});
    }
    if (req.method === "POST") {
      const newBody = { ...req.body, token: "233" };
      secureReq = req.clone({body: newBody});
    }
    // 请求发出前
    return next.handle(secureReq).pipe(
      tap(r => {
        // 请求响应时
        console.log(r);
      }),
    );
  }
}
posted @ 2018-03-16 12:43  Ajanuw  阅读(50)  评论(0)    收藏  举报