About Http request principle in angular2 (detailed tutorial)

亚连
Release: 2018-06-12 15:01:35
Original
1805 people have browsed it

This article mainly introduces the principle and usage of Http requests in angular2, and analyzes the http related modules in AngularJS to implement http service requests and corresponding related operation techniques in the form of examples. Friends in need can refer to it

The examples in this article describe the principles and usage of HTTP requests in angular2. Share it with everyone for your reference, the details are as follows:

Provide HTTP service

##HttpModuleis not the core module of Angular . It is an optional method used by Angular for web access, and is located in a separate satellite module called@angular/http.

Edit app.module.ts

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

angular-in-memory-web-api

npm install angular-in-memory-web-api --save-dev
Copy after login

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"
Copy after login

app/mock/user_data_memory_mock.ts data used in previous testing

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}; } }
Copy after login

Edit app.module.ts

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

Import InMemoryWebApiModule and add it to the module’s imports array. InMemoryWebApiModule simulates the back-end service of the Http client


forRoot()The configuration method requires an instance of the UserMemoryMockService class to fill data into the memory database

Edit 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 { const url = `${this.USERURL}/?name=${name}`; return this.http.get(url) .toPromise() .then(response => response.json().data as User) .catch(this.handleError); } getUsers(): Promise { 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 { 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{ console.log('An error occurred :', error); return Promise.reject(error.message); } }
Copy after login

edit 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)); } }
Copy after login

HTTP Promise

Angular's http.get returns an RxJS Observable object. Observable is a powerful way to manage asynchronous data streams.

Now, we first use the toPromise method to directly convert the Observable into a Promise object

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JavaScript recursive traversal and non-recursive traversal

VUE personal summary (problems encountered)

Nuxt.js Vue server-side rendering exploration

What are the differences between let and var defined variables in js?

In vue, there is a problem about watch not being able to detect changes in object properties

The above is the detailed content of About Http request principle in angular2 (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!