【问题标题】:angular 4 best practice: load global data via service and store it角度 4 最佳实践:通过服务加载全局数据并存储
【发布时间】:2018-03-09 21:00:01
【问题描述】:

我想构建一个 Angular 4 应用程序,我可以在其中从数据库中搜索用户并使用我在不同路线上找到的人的信息。我目前的问题是,如果我通过服务加载一些数据,更改路线并返回,数据会再次加载。

我的服务:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';

@Injectable()
export class GlobalDataService {
cachedData: Observable<any>;

getData() {
    if (this.cachedData) {
      console.log('cache data found');
      return Observable.of(this.cachedData);
    } else {
      console.log('cache data NOT found');
      return this.http.get('https://56e05c3213da80110013eba3.mockapi.io/api/todos')
            .map(res => res.json())
            .do((data) => {
              this.cachedData = data;
            })
        .share();
    }
  }

我的组件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators} from '@angular/forms';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/map';
import { GlobalDataService } from '../../services/global-data.service';
@Component({
   selector: 'app-dashboard',
   templateUrl: './dashboard.component.html',
   styleUrls: ['./dashboard.component.css'],
   providers: [GlobalDataService]
})
export class DashboardComponent implements OnInit {
   todos: Observable<any[]>;
   constructor(private globalDataService: GlobalDataService) { }
   ngOnInit() {
      this.globalDataService.getData().subscribe(
        (resp) => {
            this.todos = resp;
        }
    );
}}

当我运行该应用程序时,我得到 console.log 'NOT found' 并且数据被加载,正如它应该的那样,但是当我改变路线并切换回来时,它再次被加载,这是不正确的。

我希望您可以帮助我提供一个完整的工作示例,以便我查看代码。也许我错过了什么。

如果您需要更多信息,请随时询问。

【问题讨论】:

标签: angular service routing shared-data


【解决方案1】:

您是否多次提供该服务?您应该只注册一次服务。

我在您的仪表板组件中看到它:

providers: [GlobalDataService]

您在任何其他组件或模块中是否有这样的列表?

要共享一项服务,只能注册一次:

  • 在组件树的根目录(如应用组件)
  • OR 在模块中而不是在组件中。

如果你多次注册它,它不会作为一个单例工作,你也不会得到共享数据。

【讨论】:

    猜你喜欢
    • 2014-03-06
    • 2011-01-25
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多