怎么在angular2中實(shí)現(xiàn)一個(gè)Http請(qǐng)求

怎么在angular2中實(shí)現(xiàn)一個(gè)Http請(qǐng)求?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

創(chuàng)新互聯(lián)專注于北林企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城網(wǎng)站制作。北林網(wǎng)站建設(shè)公司,為北林等地區(qū)提供建站服務(wù)。全流程按需定制,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

提供HTTP服務(wù)

HttpModule并不是Angular的核心模塊。 它是Angular用來進(jìn)行Web訪問的一種可選方式,并位于一個(gè)名叫@angular/http的獨(dú)立附屬模塊中.

編輯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"

之前測(cè)試時(shí)用的app/mock/user_data_memory_mock.ts數(shù)據(jù)

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),
 ]
})

導(dǎo)入InMemoryWebApiModule并將其加入到模塊的imports數(shù)組。 InMemoryWebApiModule將Http客戶端模擬的后端服務(wù)
forRoot()配置方法需要UserMemoryMockService類實(shí)例,用來向內(nèi)存數(shù)據(jù)庫填充數(shù)據(jù)

編輯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返回一個(gè) RxJS 的Observable對(duì)象。 Observable是一個(gè)管理異步數(shù)據(jù)流的強(qiáng)力方式。

現(xiàn)在,我們先利用toPromise方法把Observable直接轉(zhuǎn)換成Promise對(duì)象

看完上述內(nèi)容,你們掌握怎么在angular2中實(shí)現(xiàn)一個(gè)Http請(qǐng)求的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

文章標(biāo)題:怎么在angular2中實(shí)現(xiàn)一個(gè)Http請(qǐng)求
地址分享:http://muchs.cn/article34/iidepe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、電子商務(wù)、定制開發(fā)、微信小程序、軟件開發(fā)、品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計(jì)公司