首頁 >web前端 >js教程 >在angular2中有關Http請求原理(詳細教學)

在angular2中有關Http請求原理(詳細教學)

亚连
亚连原創
2018-06-12 15:01:351918瀏覽

這篇文章主要介紹了angular2中Http請求原理與用法,結合實例形式分析了AngularJS中http相關模組實現http服務請求與相應的相關操作技巧,需要的朋友可以參考下

#本文實例講述了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 heroes
GET api/heroes/42    // the character with id=42
GET 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(&#39;Get User!&#39;);
    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(&#39;An error occurred :&#39;, error);
    return Promise.reject(error.message);
  }
}

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

import { Component, OnInit } from &#39;@angular/core&#39;;
import { Logger } from &#39;../../service/logger.service&#39;;
import { UserService } from &#39;../../service/user.restful.service&#39;;
import { User } from &#39;../../model/User&#39;;
import { Subject } from &#39;rxjs/Subject&#39;;
@Component({
 selector: &#39;app-loginform&#39;,
 templateUrl: &#39;./app.loginform.html&#39;,
 styleUrls: [&#39;./app.loginform.css&#39;],
 providers: [
  Logger,
  UserService
 ]
})
export class AppLoginFormComponent implements OnInit {
  users: User[];
  submitted = false;
  model = new User(&#39;1&#39;, &#39;fangfang&#39;, 22, &#39;2290910211@qq.com&#39;, &#39;123456&#39;);
  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(&#39;user.name&#39;, user[0].name);
      console.log(&#39;user.password&#39;, user[0].password);
      if(user[0].name === this.model.name
      && user[0].password === this.model.password){
        this.Log.log(&#39;login success!&#39;);
        this.submitted = true;
      }else{
        this.Log.log(&#39;login failed!&#39;);
        this.submitted = false;
      }
    })
    .catch(errorMsg => console.log(errorMsg));
  }
}

# HTTP Promise

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

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

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

JavaScript遞歸遍歷與非遞歸遍歷

VUE 個人總結(碰到的問題)

Nuxt.js Vue服務端渲染摸索

#js中let和var定義變數的差別有哪些?

在vue中有關watch偵測到不到物件屬性的變化方面的問題

以上是在angular2中有關Http請求原理(詳細教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn