SoFunction
Updated on 2025-04-12

Detailed explanation of the principle and usage of Http requests in angular2

This article describes the principles and usage of Http requests in angular2. Share it for your reference, as follows:

Provide HTTP services

HttpModuleNot the core module of Angular. It is an optional method used by Angular to perform web access and is located in a name@angular/httpIndependent attached module.

edit

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//42 // ignores the ".json"

The app/mock/user_data_memory_mock.ts data used in previous tests

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@', '123456'),
    new User('chenjianhua_b', 22, '2290910211@', '123456'),
    new User('chenjianhua_c', 23, '2290910211@', '123456'),
    new User('chenjianhua_d', 24, '2290910211@', '123456'),
    new User('chenjianhua_e', 25, '2290910211@', '123456'),
    new User('chenjianhua_f', 26, '2290910211@', '123456'),  
  ];
  return {users};
 }
}

edit

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

Import the InMemoryWebApiModule and add it to the module's imports array. InMemoryWebApiModule backend service that simulates Http client
forRoot()The configuration method requires a UserMemoryMockService class instance to fill data into the in-memory database.

Edit app/service/

import {Injectable} from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { User } from '../model/User';
import { Logger } from './';
@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 = `${}/?name=${name}`;
  return (url)
    .toPromise()
    .then(response => ().data as User)
    .catch();
  }
  getUsers(): Promise<User[]> {
    ('Get User!');
    return ()
    .toPromise()
    .then(response => ().data as User[])
    .catch();
  }
  create(name: string): Promise<User> {
  return 
    .post(, ({name: name}), {headers: })
    .toPromise()
    .then(res => ().data as User)
    .catch();
  }
  private handleError(error: any): Promise<any>{
    ('An error occurred :', error);
    return ();
  }
}

Edit app/components/app-loginform/

import { Component, OnInit } from '@angular/core';
import { Logger } from '../../service/';
import { UserService } from '../../service/';
import { User } from '../../model/User';
import { Subject } from 'rxjs/Subject';
@Component({
 selector: 'app-loginform',
 templateUrl: './',
 styleUrls: ['./'],
 providers: [
  Logger,
  UserService
 ]
})
export class AppLoginFormComponent implements OnInit {
  users: User[];
  submitted = false;
  model = new User('1', 'fangfang', 22, '2290910211@', '123456');
  constructor(
    private Log: Logger,
    private userService: UserService
  ){}
  ngOnInit(): void{
    
    .getUsers()
    .then( users =>  = users);
  }
  onSubmit(): void {
    ()
    .then( user => {
      ('', user[0].name);
      ('', user[0].password);
      if(user[0].name === 
      && user[0].password === ){
        ('login success!');
         = true;
      }else{
        ('login failed!');
         = false;
      }
    })
    .catch(errorMsg => (errorMsg));
  }
}

HTTP Promise

Angular returns an RxJS Observable object. Observable is a powerful way to manage asynchronous data flows.

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

For more information about AngularJS, readers who are interested in view the topic of this site:Summary of AngularJS command operation skills》、《AngularJS Introduction and Advanced Tutorial"and"AngularJS MVC architecture summary

I hope this article will be helpful to everyone's AngularJS programming.