GVKun编程网logo

在Angular 4中从HttpClient缓存数据(angular项目缓存问题)

27

对于在Angular4中从HttpClient缓存数据感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解angular项目缓存问题,并且为您提供关于Angular11httpClient顺序请

对于在Angular 4中从HttpClient缓存数据感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解angular项目缓存问题,并且为您提供关于Angular 11 httpClient 顺序请求、Angular 2到4升级,从Http转移到HttpClient、Angular 4 HttpClient 查询参数、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)的宝贵知识。

本文目录一览:

在Angular 4中从HttpClient缓存数据(angular项目缓存问题)

在Angular 4中从HttpClient缓存数据(angular项目缓存问题)

我有一个问题,使我的缓存更简单.我认为有更好的方法来做到这一点.我的问题是我必须在每个get()函数中执行此“缓存”代码,这会导致代码更长.有谁帮助如何做到这一点最好的方式?谢谢.这是我的代码如下.我在我的代码中做的是我在news.service.ts中执行get()函数以从http获取数据,并在我的新闻列表中订阅它.

news.service.ts

getAllNews() {

    if(this.newslist != null) {
      return Observable.of(this.newslist);
    } 

    else {

      return this.httpClient
        .get('http://sample.com/news')
        .map((response => response))
        .do(newslist => this.newslist = newslist)
        .catch(e => {
            if (e.status === 401) {
                return Observable.throw('Unauthorized');           
            }

        });
    }
  }

news-list.service.ts

this.subscription = this.newsService.getAllNews()
      .subscribe(
        (data:any) => {
          console.log(data);
          this.newslists = data.data.data;
        },error => {
          this.authService.logout()
          this.router.navigate(['signin']);
        });
  }

解决方法

如果您打算使用通用的,可以用于不同的API调用或服务,那么您可以执行以下操作:

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable,of } from 'rxjs';
import { map } from 'rxjs/operators';

class CacheItem<T> {
  url: string;
  timestampCached: number;
  data: T;
}

@Injectable({
  providedIn: 'root'
})
export class MyCachedHttpClient {
  cache: CacheItem<any>[] = [];

  constructor(
    private http: HttpClient,) { }

  get<T>(url: string,cacheTime?: number,forceRefresh: boolean = false)
  : Observable<T> {
    let cachedItem: CacheItem<T> = this.getCachedItem<T>(url);

    if (cachedItem != undefined && !forceRefresh) {
      let expireDate = cachedItem.timestampCached + cacheTime;
      if (Date.Now() < expireDate) {
        return of(cachedItem.data);
      }
    }

    return this.http.get<T>(url).pipe(
      map(data => {
        if (cacheTime) { // if we actually want to cache the result
          if (cachedItem == undefined) {
            cachedItem = new CacheItem();
            cachedItem.url = url;
            this.cache.push(cachedItem);
          }
          cachedItem.data = data;
          cachedItem.timestampCached = Date.Now();
        }
        return data;
      })
    );
  }

  private getCachedItem<T>(url: string): CacheItem<T> {
    return this.cache.find(item => item.url == url);
  }
}

然后在任何地方使用MyCachedHttpClient而不是HttpClient.

笔记:

>这是针对Angular 6 / RxJS 6.如果您在下面,请参阅编辑历史记录中的代码.>这只是一个基本的实现,隐藏了HttpClient的get()函数的许多功能,因为我没有在这里重新实现options参数.

Angular 11 httpClient 顺序请求

Angular 11 httpClient 顺序请求

如何解决Angular 11 httpClient 顺序请求?

我有一个前端需要通过休息端点添加一组项目。

我可以很好地进行一次调用,并且我相信我了解订阅 observable 的基础知识。确实,我可以成功编码单个请求并正确处理响应。

我不知道的是如何封装对服务器的多个调用。我想要一个返回 observable 的函数,这样它就像一个单一的调用。

知道状态并且确实插入是很重要的。

// the complete payload.
export class SignupDto {
  companyInfo: CompanyInfo;
  storeInfo: StoreDto [];
  constructor(storeCount: number) {
    this.companyInfo = new CompanyInfo();
    this.storeInfo = new Array(storeCount);
  }
}



// my attempt.
 public postCompanyInfo(store: SignupModel) {
    const payload = MappingService.MapToPayload(store);
    const headers = new HttpHeaders().set(''Content-Type'',''application/json'');
    const config = { headers: headers,observe: "response" as ''body'' };
    const Path = ''signup/'';
    const URL = `${this.Protocol_Domain_Port}${Path}`;
    this.httpClient.post(URL,payload.companyInfo,config).subscribe(
      (resp: any) => { if( resp.status === 201 ) { this.onInsertStores(payload.storeInfo,resp._links.stores.href); } },)
  }

  public onInsertStores(storeInfo: StoreDto [],URL: string) {
    const headers = new HttpHeaders().set(''Content-Type'',observe: "response" as ''body'' };
    if( !!storeInfo && storeInfo.length > 0 ) {
      this.httpClient.post(URL,storeInfo[0],config).subscribe(
          (resp: any) => { if( resp.status === 201 ) { storeInfo.shift(); this.onInsertStores(storeInfo,URL); } },);
    }
  }

该公司确实发布了,但随后商店在subscriber.js 调用堆栈的深处失败了。

catch (err) {
    this.unsubscribe();
    if (config.useDeprecatedSynchronousErrorHandling) {
        throw err;

我认为我可以使用某种递归解决方案,但即使有效,我也不知道如何在最后返回成功或失败的状态代码。

所以,我需要一种方法来首先插入公司信息,然后依次插入每个商店。如果出现故障,请停止并返回该错误。或者,如果他们都成功了,则返回成功。

我遇到了一种叫做管道映射器的东西,但老实说,我不理解它。所以,我不知道它是否能解决我的问题。

以防万一,这是我要发送的内容的模型。

{
  "companyInfo": {
    "companyAddress": {
      "address1": "1515 Elm St.","address2": "Other Suit","city": "Out of Dallas","state": "TN","zipcode": "77733"
    },"bankAddress": {
      "address1": "1717 Elm St.","address2": "broken Suit","city": "USSN Dallas","state": "LA","zipcode": "33377"
    },"companyName": "Test Company is my name!","companyTaxID": "999-99-9999","bankAccountNumber": "1000000001","bankRoutingNumber": "2000000002","bankName": "We got yo cash!","bankTelephone": "(666) 555-1212","bankFax": "(555) 555-1212","accountingContactFirstName": "Testitch","accountingContactLastName": "McTestersen","accountingContactEmail": "Testitch.McTestersen@Testy.co","accountingContactTelephone": "(444) 555-1212","accountingContactFax": "(333) 555-1212"
  },"storeInfo": [
    {
      "storeAddress": {
        "address1": "1313 Elm St.","address2": "Spare Suit","city": "Near Dallas","state": "TX","zipcode": "70033"
      },"storeName": "Test Co.","customerStoreID": "Test Co Stores #0","email": "Test@Testy.co","telephone": "(888) 555-1212","fax": "(777) 555-1212","storeType": "AUTO_FULL_SERVICE","posType": "SCANMASTER","mnspType": "PAYSAFE"
    },{
      "storeAddress": {
        "address1": "1313 Elm St.","customerStoreID": "Test Co Stores #1","customerStoreID": "Test Co Stores #2","mnspType": "PAYSAFE"
    }
  ]
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Angular 2到4升级,从Http转移到HttpClient

Angular 2到4升级,从Http转移到HttpClient

我在Angular2上有一个大型应用程序,现在移植到Angular4.但是,它仍然使用Http服务.

我意识到Angular4有HttpClient,据说比Http服务更好.但是,我很担心改用HttpClient,因为它被用于很多地方和相应的单元测试.

我想知道,从Http迁移到HttpClient的最佳方法是什么?从代码和单元测试的角度来看,我应该考虑哪些事情?

我想转移到HttpClient的另一个原因是使用拦截器?是否有必要更改为HttpClient?

请指教.提前谢谢了.

只是我的经验.

我记得我最大的问题是在每个http调用中删除地图.

否则你只需要导入HttpClientModule并注入HttpClient服务而不是Http.

此外,单元测试也有一些变化.所以,如果你有单元测试,你会有更多的工作.使用HttpClient单元测试变得更加容易. Angular有很棒的文档,所以我认为这不会是个大问题.至少对我来说,理解这些新东西并没有任何问题.

您可以查看此文章以获取更多信息:http://brianflove.com/2017/07/21/migrating-to-http-client/.

Angular 4 HttpClient 查询参数

Angular 4 HttpClient 查询参数

我一直在寻找一种将查询参数传递到使用 new 的 API
调用HttpClientModule的方法HttpClient,但尚未找到解决方案。使用旧Http模块,您将编写类似这样的内容。

getNamespaceLogs(logNamespace) {

    // Setup log namespace query parameter
    let params = new URLSearchParams();
    params.set('logNamespace',logNamespace);

    this._Http.get(`${API_URL}/api/v1/data/logs`,{ search: params })
}

这将导致对以下 URL 的 API 调用:

localhost:3001/api/v1/data/logs?logNamespace=somelogsnamespace

但是,新HttpClient get()方法没有search属性,所以我想知道在哪里传递查询参数?

Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)

Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)

链接
开发工具:Visual Studio Code

在Angular 4.3中引入了新的HttpClientModule。 这个新模块可以在@ angular / common / Http包中找到,并且可以完全重新实现前一个HttpModule。新的HttpClient服务包含在HttpClientModule中,可用于启动HTTP请求并处理应用程序中的响应。

安装 4.3 项目

开始Angular 4.3项目第一步。最简单的是用Angular CLI (Angular command line interface).

  1. 如果系统还没有安装过Angular CLI ,先要执行下面的命令安装最新版(-g:全局安装):
    npm install -g @angular/cli@latest

    如果有安装cnpm,可用cnpm,下载速度更快
    cnpm install -g @angular/cli@latest
  2. 新建一个文件夹ng_http,用来存放项目。命令行切换到此目录,然后用VS Code打开。
    cd D:\Angular\NG_App
    code .
  3. 接着,就可以使用 ng命令了开始一个新的Angular 项目了:
    ng new nghttp01
    如果报错,并在错误日志记录总显示
    integrity checksum Failed when using sha512
    npm4升级npm5,在运行 npm install 时,可能会包这样的错误,执行
    npm cache clean --force
    删除项目文件夹,重新执行。
    ng new nghttp01
    执行成功后会产生 nghttp01文件夹与项目模板,依赖性也会自动安装。
  4. 检查并确认 package.json 中Angular相关所有依赖版本 号 >4.3.0。
  5. package.json 文件做过更新后,命令行中切换到nghttp01下,执行下面命令更新
    npm install

在项目中启用 HttpClient

1。为了在项目components 中使用 HttpClient 服务,第一步就是要在Angular应用中把 HttpClientModule 包含进来。首先在应用根module中导入 HttpClient module,对应文件app.module.ts。

import { browserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';//新增行
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],imports: [
    browserModule,HttpClientModule //新增行
  ],providers: [],bootstrap: [AppComponent]
})

2。上一步在根 Module 导入了HttpClientModule ,就可以在components中使用HttpClient了。使用HttpClient第一步是导入(import),还必须要注入(inject )到component class的构造函数中。如下所示:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';//新增行
@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private http: HttpClient){//新增行,httpclient注入到构造函数中,以使HttpClient可用。
  }
}

3。HttpClient使用XMLHttpRequest浏览器API来执行HTTP请求。 为了执行特定类型的HTTP请求,可以使用以下与HTTP动词相对应的方法:
**get
post
put
delete
patch
head
jsonP**

使用HttpClient 请求数据

1。 简单示例:使用 GitHub’s REST API 请求用户数据。修改app.component.ts代码(完整):

import { Component,OnInit } from '@angular/core';//新增导入OnInit
import { HttpClient } from '@angular/common/http';//新增行
@Component({
  selector: 'app-root',styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {//新增implements OnInit
  title = 'app';
  results = '';
  constructor(private http: HttpClient){///新增行,httpclient注入到构造函数中,以使HttpClient可用。
  }
  //新增ngOnInit()方法
  ngOnInit(): void {    this.http.get('https://api.github.com/users/seeschweiler').subscribe(data => {
      console.log(data);
    });
  }
}

2。项目启动:VS Code命令行执行。网页访问http://localhost:4200/
ng serve


我们今天的关于在Angular 4中从HttpClient缓存数据angular项目缓存问题的分享已经告一段落,感谢您的关注,如果您想了解更多关于Angular 11 httpClient 顺序请求、Angular 2到4升级,从Http转移到HttpClient、Angular 4 HttpClient 查询参数、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)的相关信息,请在本站查询。

本文标签: