angular2中Http請求原理與用法詳解,angular2詳解

來源:互聯網
上載者:User

angular2中Http請求原理與用法詳解,angular2詳解

本文執行個體講述了angular2中Http請求原理與用法。分享給大家供大家參考,具體如下:

提供HTTP服務

HttpModule並不是Angular的核心模組。 它是Angular用來進行Web訪問的一種可選方式,並位於一個名叫@angular/http的獨立附屬模組中.

編輯app.module.ts

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

angular-in-memory-web-api

npm install angular-in-memory-web-api --save-dev

This in-memory web api service processes an HTTP request and returns an Observable of HTTP Response object in the manner of a RESTy web api.

:base/:collectionName/:id?GET api/heroes     // all heroesGET api/heroes/42    // the character with id=42GET api/heroes?name=^j // 'j' is a regex; returns heroes whose name starting with 'j' or 'J'GET api/heroes.json/42 // ignores the ".json"

之前測試時用的app/mock/user_data_memory_mock.ts資料

import {User} from '../model/User';import { InMemoryDbService } from 'angular-in-memory-web-api';export class UserDataMemoryMock implements InMemoryDbService{ createDb() {  const users: User[] = [    new User('chenjianhua_a', 21, '2290910211@qq.com', '123456'),    new User('chenjianhua_b', 22, '2290910211@qq.com', '123456'),    new User('chenjianhua_c', 23, '2290910211@qq.com', '123456'),    new User('chenjianhua_d', 24, '2290910211@qq.com', '123456'),    new User('chenjianhua_e', 25, '2290910211@qq.com', '123456'),    new User('chenjianhua_f', 26, '2290910211@qq.com', '123456'),    ];  return {users}; }}

編輯app.module.ts

import { InMemoryWebApiModule } from 'angular-in-memory-web-api';import { UserDataMemoryMock } from './mock/user_data_memory_mock';@NgModule({ imports: [  InMemoryWebApiModule.forRoot(UserDataMemoryMock), ]})

匯入InMemoryWebApiModule並將其加入到模組的imports數組。 InMemoryWebApiModule將Http用戶端類比的後端服務
forRoot()配置方法需要UserMemoryMockService類執行個體,用來向記憶體資料庫填充資料

編輯app/service/user.restful.service.ts

import {Injectable} from '@angular/core';import { Headers, Http } from '@angular/http';import 'rxjs/add/operator/toPromise';import { User } from '../model/User';import { Logger } from './logger.service';@Injectable()export class UserService {  private USERURL = 'api/users';  private headers = new Headers({'Content-Type': 'application/json'});  constructor(private Log: Logger,  private http: Http) { }  getUserByName(name: string): Promise<User> {  const url = `${this.USERURL}/?name=${name}`;  return this.http.get(url)    .toPromise()    .then(response => response.json().data as User)    .catch(this.handleError);  }  getUsers(): Promise<User[]> {    console.log('Get User!');    return this.http.get(this.USERURL)    .toPromise()    .then(response => response.json().data as User[])    .catch(this.handleError);  }  create(name: string): Promise<User> {  return this.http    .post(this.USERURL, JSON.stringify({name: name}), {headers: this.headers})    .toPromise()    .then(res => res.json().data as User)    .catch(this.handleError);  }  private handleError(error: any): Promise<any>{    console.log('An error occurred :', error);    return Promise.reject(error.message);  }}

編輯app/components/app-loginform/app.loginform.ts

import { Component, OnInit } from '@angular/core';import { Logger } from '../../service/logger.service';import { UserService } from '../../service/user.restful.service';import { User } from '../../model/User';import { Subject } from 'rxjs/Subject';@Component({ selector: 'app-loginform', templateUrl: './app.loginform.html', styleUrls: ['./app.loginform.css'], providers: [  Logger,  UserService ]})export class AppLoginFormComponent implements OnInit {  users: User[];  submitted = false;  model = new User('1', 'fangfang', 22, '2290910211@qq.com', '123456');  constructor(    private Log: Logger,    private userService: UserService  ){}  ngOnInit(): void{    this.userService    .getUsers()    .then( users => this.users = users);  }  onSubmit(): void {    this.userService.getUserByName(this.model.name)    .then( user => {      console.log('user.name', user[0].name);      console.log('user.password', user[0].password);      if(user[0].name === this.model.name      && user[0].password === this.model.password){        this.Log.log('login success!');        this.submitted = true;      }else{        this.Log.log('login failed!');        this.submitted = false;      }    })    .catch(errorMsg => console.log(errorMsg));  }}

HTTP Promise

Angular 的http.get返回一個 RxJS 的Observable對象。 Observable是一個管理非同步資料流的強力方式。

現在,我們先利用toPromise方法把Observable直接轉換成Promise對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.