HTTP请求效率Angular 4+ [英] HTTP request efficiency Angular 4+

查看:67
本文介绍了HTTP请求效率Angular 4+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于通过Angular发出的http请求,我有一个非常广泛但简单的问题.我有一个使用Angular http请求的Ionic应用程序,但是我不确定是否会充分利用Angular所提供的速度和效率.我当前的POST请求代码:

I have a very broad, but simple question regarding http requests via Angular. I have an Ionic app using Angular http requests, but I'm not sure if I'm making the most out of what Angular has to offer for speed and efficiency. My current code for my POST request:

页面发送数据.ts:

//calls provider function  
this.stemAPI.submitBOLData(this.submitAllData,this.reap.token).then((result) =>{
   //API response handled here               
      }, (err) => {
          //Error handled here 
        });

provider .ts

provider .ts

import { HttpClient,HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
// import { Observable } from 'rxjs/Observable';
// import { interval } from 'rxjs/observable/interval';
// import { of } from 'rxjs/observable/of';
// import { _throw } from 'rxjs/observable/throw';
// import { mergeMap, retry } from 'rxjs/operators';
import { retry } from 'rxjs/operators';

@Injectable()
  constructor(public http: HttpClient) {}
  export class StemApiProvider {
  //POST form submitBOL
    submitBOLData(data,authToken){
      //console.log(data);
      const httpOptions = {
          headers: new HttpHeaders({
              'Accept': 'application/json, text/plain',
              'Content-Type':  'application/json',
              'Authorization': authToken
            })
  };
   return new Promise((resolve, reject) => {
     this.http.post(this.apisubmitbolUrl, JSON.stringify(data), httpOptions)
     .subscribe(res=>  {
       resolve(res);
     }, (err) => {
       reject(err);
     });
   });
  }
 }

该呼叫工作正常,但我知道可以提高效率.另外,我知道rxjs包会在调用失败时提供重试"之类的功能,但是我不确定该如何实现.

The call works fine, but I know there is more efficiency that can be added. Also, I know the rxjs package offers functionality like "retry" if the call fails, but I'm not sure how exactly that can be implemented.

此问题的最大原因是,我的客户可能会在没有最佳蜂窝连接的区域中使用该应用程序,因此API调用可能会花费更长的时间,如果连接中断,我想知道我可以利用哪些工具为用户提供其他选择.

The biggest reason for this question is because my clients will potentially be using the app in areas where there isn't the best cellular connection so the API calls will potentially take longer and I if the connection happens to break I want to know what tools I can utilize to give user other options.

package.json

package.json

{
  "name": "Test Project",
  "version": "0.6.0",
  "author": "",
  "homepage": "",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/animations": "5.2.10",
    "@angular/common": "5.2.10",
    "@angular/compiler": "5.2.10",
    "@angular/compiler-cli": "5.2.10",
    "@angular/core": "5.2.10",
    "@angular/forms": "5.2.10",
    "@angular/http": "5.2.10",
    "@angular/platform-browser": "5.2.10",
    "@angular/platform-browser-dynamic": "5.2.10",
    "@ionic-native/app-version": "^4.15.0",
    "@ionic-native/camera": "^4.15.0",
    "@ionic-native/core": "4.11.0",
    "@ionic-native/device": "^4.15.0",
    "@ionic-native/file": "^4.15.0",
    "@ionic-native/file-transfer": "^4.15.0",
    "@ionic-native/geolocation": "^4.15.0",
    "@ionic-native/ionic-webview": "^5.0.0-beta.21",
    "@ionic-native/network": "^4.15.0",
    "@ionic-native/splash-screen": "4.7.0",
    "@ionic-native/status-bar": "4.7.0",
    "@ionic/pro": "^2.0.3",
    "@ionic/storage": "^2.2.0",
    "angular2-signaturepad": "^2.8.0",
    "cordova-android": "7.1.1",
    "cordova-browser": "5.0.3",
    "cordova-ios": "4.5.5",
    "cordova-plugin-app-version": "^0.1.9",
    "cordova-plugin-camera": "^4.0.3",
    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-file": "6.0.1",
    "cordova-plugin-file-transfer": "1.7.1",
    "cordova-plugin-geolocation": "^4.0.1",
    "cordova-plugin-ionic": "5.2.5",
    "cordova-plugin-ionic-keyboard": "^2.1.3",
    "cordova-plugin-ionic-webview": "^2.2.0",
    "cordova-plugin-network-information": "^2.0.1",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-webview": "0.0.1",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-sqlite-storage": "2.4.0",
    "ionic-angular": "^3.9.2",
    "ionic-select-searchable": "^2.10.0",
    "ionic-selectable": "^3.0.3",
    "ionicons": "3.0.0",
    "rxjs": "5.5.11",
    "sw-toolbox": "3.6.0",
    "ts-md5": "^1.2.4",
    "ws": "^3.3.3",
    "zone.js": "0.8.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.2.0",
    "typescript": "~2.6.2"
  },
  "description": "An Ionic project",
  "cordova": {
    "plugins": {
      "cordova-plugin-geolocation": {
        "GEOLOCATION_USAGE_DESCRIPTION": "To locate you"
      },
      "cordova-plugin-device": {},
      "cordova-plugin-app-version": {},
      "cordova-plugin-camera": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-ionic-keyboard": {},
      "cordova-plugin-network-information": {},
      "cordova-sqlite-storage": {},
      "cordova-plugin-ionic-webview": {
        "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+"
      },
      "cordova-plugin-ionic": {
        "APP_ID": "",
        "CHANNEL_NAME": "Master",
        "UPDATE_METHOD": "background",
        "UPDATE_API": "https://api.ionicjs.com",
        "MAX_STORE": "2",
        "MIN_BACKGROUND_DURATION": "30"
      }
    },
    "platforms": [
      "browser",
      "ios",
      "android"
    ]
  }
}

推荐答案

首先,如果您使用的是Http,我建议您使用HttpClient.它是在Angular 4.3中引入的,如果您使用它,则无需执行.map(res => res.json())

First of all, I'd urge you to use HttpClient if you're using Http. It was introduced in Angular 4.3 and if you use that, you aren't required to do .map(res => res.json())

您首先需要将其HttpClientModule添加到@NgModuleimports数组中.

You will first have to add it HttpClientModule to the imports array of your @NgModule.

import { HttpClientModule } from '@angular/common/http'
...
@NgModule({
  ...
  imports: [..., HttpClientModule, ...],
  ...
})

角度HttpClient返回Observable,而不返回Promise.这样可以给您带来优势,因为您可以使用retry n次这样的运算符,以防在向用户显示错误消息之前出现网络错误.

Angular HttpClient returns Observables and not Promises. That gives you an edge as you can use operators like retry n times in case there's a network error before showing the user an error message.

您的代码可以进行相同的重构.

Your code can be significantly refactored for the same.

import 'rxjs/add/operator/retry';
...
submitBOLData(data, authToken) {
  const httpOptions = {
    headers: new HttpHeaders({
      'Accept': 'application/json, text/plain',
      'Content-Type': 'application/json',
      'Authorization': authToken
    })
  };

  return this.http.post(this.apisubmitbolUrl, data, httpOptions)
    .retry(3); // This will retry 3 times in case there's an error
}

使用此功能的地方:

this.stemAPI.submitBOLData(this.submitAllData, this.reap.token)
  .subscribe(
    res => { /* Do what you want with this error */ }, 
    err => { /* Error handled here */ }
   );

这是一个

Here's a Sample StackBlitz for your ref.

这篇关于HTTP请求效率Angular 4+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆