Home Web Front-end JS Tutorial About Http request principle in angular2 (detailed tutorial)

About Http request principle in angular2 (detailed tutorial)

Jun 12, 2018 pm 03:01 PM
http request

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

##HttpModule is 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<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(&#39;Get User!&#39;);
    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(&#39;An error occurred :&#39;, error);
    return Promise.reject(error.message);
  }
}
Copy after login

edit app/components/app-loginform/app.loginform.ts

import { Component, OnInit } from &#39;@angular/core&#39;;
import { Logger } from &#39;../../service/logger.service&#39;;
import { UserService } from &#39;../../service/user.restful.service&#39;;
import { User } from &#39;../../model/User&#39;;
import { Subject } from &#39;rxjs/Subject&#39;;
@Component({
 selector: &#39;app-loginform&#39;,
 templateUrl: &#39;./app.loginform.html&#39;,
 styleUrls: [&#39;./app.loginform.css&#39;],
 providers: [
  Logger,
  UserService
 ]
})
export class AppLoginFormComponent implements OnInit {
  users: User[];
  submitted = false;
  model = new User(&#39;1&#39;, &#39;fangfang&#39;, 22, &#39;2290910211@qq.com&#39;, &#39;123456&#39;);
  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(&#39;user.name&#39;, user[0].name);
      console.log(&#39;user.password&#39;, user[0].password);
      if(user[0].name === this.model.name
      && user[0].password === this.model.password){
        this.Log.log(&#39;login success!&#39;);
        this.submitted = true;
      }else{
        this.Log.log(&#39;login failed!&#39;);
        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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to send email using PHP HTTP request How to send email using PHP HTTP request May 21, 2023 pm 07:10 PM

PHP is a widely used programming language, and one of its common applications is sending emails. In this article, we will discuss how to send emails using HTTP requests. We will introduce this topic from the following aspects: What is an HTTP request? Basic principles of sending emails using PHP. Sending HTTP requests. Sample code for sending emails. What is an HTTP request? An HTTP request refers to a request sent to a web server to obtain a web resource. . HTTP is a protocol used in web browsers and we

From start to finish: How to use php extension cURL to make HTTP requests From start to finish: How to use php extension cURL to make HTTP requests Jul 29, 2023 pm 05:07 PM

From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

How to solve the problem of HTTP request connection refused in Java development How to solve the problem of HTTP request connection refused in Java development Jun 29, 2023 pm 02:29 PM

How to solve the problem of HTTP request connection being refused in Java development. In Java development, we often encounter the problem of HTTP request connection being refused. This problem may occur because the server side restricts access rights, or the network firewall blocks access to HTTP requests. Fixing this problem requires some adjustments to your code and environment. This article will introduce several common solutions. Check the network connection and server status. First, confirm that your network connection is normal. You can try to access other websites or services to see

Cause analysis: HTTP request error 504 gateway timeout Cause analysis: HTTP request error 504 gateway timeout Feb 19, 2024 pm 05:12 PM

Brief introduction to the reason for the http request error: 504GatewayTimeout: During network communication, the client interacts with the server by sending HTTP requests. However, sometimes we may encounter some error messages during the process of sending the request. One of them is the 504GatewayTimeout error. This article will explore the causes and solutions to this error. What is the 504GatewayTimeout error? GatewayTimeo

Solution: Socket Error when handling HTTP requests Solution: Socket Error when handling HTTP requests Feb 25, 2024 pm 09:24 PM

http request error: Solution to SocketError When making network requests, we often encounter various errors. One of the common problems is SocketError. This error is thrown when our application cannot establish a connection with the server. In this article, we will discuss some common causes and solutions of SocketError. First, we need to understand what Socket is. Socket is a communication protocol that allows applications to

Set query parameters for HTTP requests using Golang Set query parameters for HTTP requests using Golang Jun 02, 2024 pm 03:27 PM

To set query parameters for HTTP requests in Go, you can use the http.Request.URL.Query().Set() method, which accepts query parameter names and values ​​as parameters. Specific steps include: Create a new HTTP request. Use the Query().Set() method to set query parameters. Encode the request. Execute the request. Get the value of a query parameter (optional). Remove query parameters (optional).

How to use Nginx for compression and decompression of HTTP requests How to use Nginx for compression and decompression of HTTP requests Aug 02, 2023 am 10:09 AM

How to use Nginx to compress and decompress HTTP requests Nginx is a high-performance web server and reverse proxy server that is powerful and flexible. When processing HTTP requests, you can use the gzip and gunzip modules provided by Nginx to compress and decompress the requests to reduce the amount of data transmission and improve the request response speed. This article will introduce the specific steps of how to use Nginx to compress and decompress HTTP requests, and provide corresponding code examples. Configure gzip module

How Nginx implements retry configuration of HTTP requests How Nginx implements retry configuration of HTTP requests Nov 08, 2023 pm 04:47 PM

How Nginx implements HTTP request retry configuration requires specific code examples. Nginx is a very popular open source reverse proxy server. It has powerful functions and flexible configuration options and can be used to implement HTTP request retry configuration. In network communication, sometimes the HTTP request we initiate may fail due to various reasons, such as network delay, server load, etc. In order to improve the reliability and stability of the application, we may need to retry when the request fails. The following will introduce how to use Ng

See all articles