欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angular2中Http请求原理与用法详解

程序员文章站 2024-01-16 21:20:22
本文实例讲述了angular2中http请求原理与用法。分享给大家供大家参考,具体如下: 提供http服务 httpmodule并不是angular的核心模块。 它是a...

本文实例讲述了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('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对象

更多关于angularjs相关内容感兴趣的读者可查看本站专题:《angularjs指令操作技巧总结》、《angularjs入门与进阶教程》及《angularjs mvc架构总结

希望本文所述对大家angularjs程序设计有所帮助。