欢迎来到代码驿站!

AngularJS

当前位置:首页 > 网页前端 > AngularJS

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

时间:2021-07-22 07:46:39|栏目:AngularJS|点击:

本文实例讲述了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程序设计有所帮助。

上一篇:AngularJS实现自定义指令与控制器数据交互的方法示例

栏    目:AngularJS

下一篇:Angular angular-file-upload文件上传的示例代码

本文标题:angular2中Http请求原理与用法详解

本文地址:http://www.codeinn.net/misctech/160132.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有