Angular8的使用(二):service和Http

hello_fracong發表於2019-10-10

1.service

1.1.service的建立命令

ng generate service xxx  //生成一個新服務
ng generate service xxx  --no-spec  //生成一個不帶有spec.ts的新服務

1.2.在service.ts中新增方法

import { Http } from '@angular/http';

export class AppService {
  urlRoot = 'http://localhost:8892/';

  constructor(private http: Http) { }

  queryTestWebList(urlParams: string) {
    const url = this.urlRoot + 'testuser/queryTestWeb/list/' + urlParams;
    return this.http.get(url);
  }
}

1.3.元件中呼叫service

import {AppService} from '../app.service';

export class MenuLeftComponent implements OnInit {

	constructor(
    	private service: AppService
 	 ) { }
 	 
 	 ngOnInit() {}
 	 
 	 queryTestWebList(flag: boolean) {
		this.service.queryTestWebListHttp(urlParams).subscribe(
 	 		dataJson => {
 	 			//返回結果處理
		      },
		      error => {
		
		      }
		);
 	 }
}

2.Http兩種使用

2.1.引用@angular/http的方式

2.1.1.安裝http

npm install @angular/http     //安裝http
npm install rxjs

在app.module.ts中(imports屬性新增)引入@angular/http模組,如下程式碼:

import { HttpModule, JsonpModule } from '@angular/http';
@NgModule({
	imports: [
    JsonpModule,
    HttpModule
  ]
})

2.1.2.get的使用

import { Http } from '@angular/http';
import { Observable} from 'rxjs';

constructor(
    private http: Http
  ) { }
functionXXXX () {
	this.http.get(url).subscribe(
      dataJson => {
      	// 用於處理資料
      },
      error => {
      }
    );
}

2.1.3.post的使用

2.1.3.1.傳送json格式資料

import { Injectable } from '@angular/core';
import { Http ,  RequestOptions, Headers} from '@angular/http';
import { Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class AppService {
  urlRoot = 'http://localhost:8892/';

  constructor(private http: Http) { }

  saveFormPostHttp(sq: string,
                   num: string,
                   name: string,
                   key: string,
                   value: string,
                   type: string,
                   page: string,
                   base: string,
                   ): Observable<{}> {
	    const url = this.urlRoot + 'testuser/insertTestWeb/';
	    
	    const params = JSON.parse('{"sq":' + sq + ',"num":' + num + ',' +
	      '"webName":' + name + ',"webKey":' + key + ',' +
	      '"value":' + value + ',"webType":' + type + ',' +
	      '"page":' + page + ',"base":' + base + '}');
	    const headers = new Headers(); // 使用@angular/http的Headers
	    
	    headers.append('Content-Type', 'application/json');
	    const options = new RequestOptions({ headers}); // 使用@angular/http的RequestOptions
	    
	    return this.http.post(url, params, options);
	  }
}

說明:後端如果需要使用json格式接收,或者使用 @RequestBody 接收

2.1.3.2.傳送form表單資料

HttpClientModule,

import { Injectable } from '@angular/core';
import { Http , URLSearchParams, RequestOptions, Headers} from '@angular/http';
import { Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class AppService {
  urlRoot = 'http://localhost:8892/';

  constructor(private http: Http) { }

  saveFormPostHttp(sq: string,
                    num: string,
                    name: string,
                    key: string,
                    value: string,
                    type: string,
                    page: string,
                    base: string,
  ): Observable<{}> {
    const url = this.urlRoot + 'testuser/insertTestWeb2';
	
	const params = new URLSearchParams();
    params.set('sq', sq);
    params.set('webNum', num);
    params.set('webName', name);
    params.set('key', key);
    params.set('value', value);
    params.set('webType', type);
    params.set('page', page);
    params.set('base', base);
	
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    const options = new RequestOptions({ headers});
    
    return this.http.post(url, params, options);
  }
}

說明
1.後端使用 @RequestParam 接收;
2.如果使用URLSearchParams,那麼Content-Type的格式就必須使用form;如果params使用的是json,則Content-Type的格式就必須使用json;
3.如果Content-Type為form,可以不寫options,使用this.http.post(url, params);即可;

2.2.引用@angular/common/http的方式

前提:在app.module.ts中(imports屬性新增)引入@angular/common/http模組,程式碼如下:

import {HttpClientModule} from '@angular/common/http';
@NgModule({
  imports: [
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

2.2.1.新建一個httpClient的service

ng generate service httpClient  --no-spec

2.2.1.get請求

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {map} from 'rxjs/operators';
import {HttpResponse} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {
  urlRoot = 'http://localhost:8892/';
  options = {
    headers: new HttpHeaders({'Content-Type': 'application/json; charset=UTF-8'})
  };
  
  constructor(private http: HttpClient) { }
  
 queryList() {
    const url = this.urlRoot + 'testuser/queryTestWeb/list/FFFFFFFF/FFFFFFFF/FFFFFFFF/FFFFFFFF/10/1';
    return this.http.get<any>(url, this.options).pipe(
      timeout(15000),
      catchError((error) => this.hanldeSomeError(error))
    );
  }
  
  private hanldeSomeError(error: any) {
    if (error.error instanceof ErrorEvent) {
      console.log(' error occurred:', error.error.message);
    } else {
      console.log(`${error.status}-${error.statusText}`);
    }
    return throwError(new Error('Server Error!'));
  }
}

說明
1.使用pipe中的rxjs方法(timeout/catchError等)對資料進行處理;
2.使用@angular/common/http的時候和使用@angular/http區別,get後面<T>作為接收資料的轉化型別(T可以是any,也可以是自定義類),不需要使用rxjs的map函式進行處理,預設是獲取body的值進行返回的;
3.options內只能包含一種型別資料,如headers,observe,params,reportProgress,responseType,withCredentials。
4.如果使用observe,如 get(url, { observe: ‘response’ }) 時,資料中提取的是完整的response,這個時候可以使用map進行處理,這個時候<T>時可以不用的。
4.呼叫方法如下:

clickQueryListByHttpClientGet() {
    this.httpClient.queryList().subscribe((data) => {
      console.log(data.list);
    });
  }

2.2.2.post請求

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http';
import {catchError, timeout} from 'rxjs/operators';
import {throwError} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {
  urlRoot = 'http://localhost:8892/';
  options = {
    headers: new HttpHeaders({'Content-Type': 'application/json; charset=UTF-8'})
  };
  
  constructor(private http: HttpClient) { }
  
 saveFormPostHttp(sq: string,
                   num: string,
                   name: string,
                   key: string,
                   value: string,
                   type: string,
                   page: string,
                   base: string,
                  ) {
    const url = this.urlRoot + 'testuser/insertTestWeb';
    const params = JSON.parse('{"sq":' + sq + ',"num":' + num + ',' +
      '"webName":' + name + ',"webKey":' + key + ',' +
      '"value":' + value + ',"webType":' + type + ',' +
      '"page":' + page + ',"base":' + base + '}');
    return this.http.post<any>(url, params, this.options).pipe(
      timeout(15000),
      catchError((error) => this.hanldeSomeError(error))
    );
  }
  
  private hanldeSomeError(error: any) {
    if (error.error instanceof ErrorEvent) {
      console.log(' error occurred:', error.error.message);
    } else {
      console.log(`${error.status}-${error.statusText}`);
    }
    return throwError(new Error('Server Error!'));
  }
}

說明
1.post<T>的T作為返回資料封裝型別,如果是json資料,可以使用any進行接收。
2.options的型別和使用均和get保持一致。
3.呼叫程式碼如下:

clickSaveHttpClientPost() {
    this.httpClient.saveFormPostHttp('502', '3', '1', '2', '4', '3', '32', '65').subscribe(dataJson => {
      console.log(dataJson.flag);
    });
  }

相關文章