簡體   English   中英

每次我使用路由導航到組件時,角度 http 獲取

[英]angular http fetching every time i navigate to component using routing

每次使用路由導航到組件時,我都使用 6.1.3 Angular HTTP 獲取。 我是角度的新手。

任何人都可以請幫忙。

我正在ngOnninit獲取數據我認為這是問題所在

在此處輸入圖片說明

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private httpDataGetter: HttpClient
  ) { }

  ngOnInit() {
    this.httpDataGetter.get('https://my-json-server.typicode.com/alifrontend499/userdatafake/profile').subscribe(responsive => {
      $(responsive).each((count, obj) => {
        this.userdata.push(obj);
      });
    }, err => {
      console.log(err);
    });
  }

  userdata = []

}

我希望當我導航到我的(如果它的主組件)中的鏈接時獲取值我使用路由它工作並且在獲取值時它也工作但是當我第一次導航時在 ngOninit 中使用 this.http.get()到 homecomponent 它獲取值這很好但是當我導航到登錄並返回 homecomponent 它再次獲取值。 我不想要。還有其他方法嗎?

如果您不想繼續重新獲取數據,那么您可以將請求移動到服務中並使用ReplaySubject為該服務實現緩存。

Angular 2緩存可觀察的http結果數據

創建服務,並保持userdata中,作為:

上門服務

@Injectable()
export class HomeService {
  private userdata;

  constructor(private http: HttpClient) { }

  getData() {
    if(!userdata) { // it will only hit api if data is not there
        this.http.get('https://my-json-server.typicode.com/alifrontend499/userdatafake/profile').subscribe(responsive => {
            this.userdata = [];
            $(responsive).each((count, obj) => {
                this.userdata.push(obj);
            });
        }, err => {
            console.log(err);
        });
    }  
  }

  get UserData() {
    return this.userdata;
  }
}

主頁組件

export class HomeComponent implements OnInit {

  constructor(
    private service: HomeService;
  ) { }

  ngOnInit() {
    this.service.getData();
  }

  get userdata() {
    return this.service.UserData;
  }
}

此外,將jQueryAngular一起使用也不是一個好習慣。

每次路由更改時,Angular 路由器都會銷毀組件,並且每次路由到“Home”時都會調用 onInit。 這是一個路由器/角度生命周期 您可以定義重用策略,如果滿足條件,路由器不會銷毀組件並在路由回來時重用組件。 (不會調用構造函數和onInit)

這個問題的解決方案是使用全局存儲(Ngrx)或在 AppModule 級別提供的全局服務。

使用單例模式獲取數據,當 null / undefined 時,如果不返回對象,則進行 http 調用。

路由重用策略

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM