Angular 2+并从api获取数据到服务

时间:2018-01-15 12:55:45

标签: angular

我有我的服务功能,这使我们可以在组件中获取和订阅数据

private _privateLessonsUrl: string = "http://localhost:3000/api/";
public privateLessons: any[];

getPrivateLessons() : any {
    return this._http.get(this._privateLessonsUrl)
      .map( (response: Response) => response.json() );    
}

任何组件

ngOnInit() {
    this._privateLessonsService.getPrivateLessons().subscribe(
        responseData => this.privateLessons = responseData
    );
}

如何实现在初始化时从该功能存储数据(在app加载时下载一次,而不是订阅),并将其保持在服务状态:

public privateLessons: any[] = [
    { ... },
    { ... },
    { ... }
];want to download it once on app loading, 

3 个答案:

答案 0 :(得分:0)

您可以创建服务以提供必要的数据。例如:

import { Subject } from 'rxjs/Subject';
import { Injectable } from '@angular/core';
import { Filter } from 'app/model/Filter';

@Injectable()
export class FilterService {

  private filterObject: Filter = null;
  private filterSource = new Subject<Filter>();
  filter = this.filterSource.asObservable();

  constructor() { }

  setFilter(newFilter: Filter) {
    this.filterObject = newFilter;
    this.filterSource.next(newFilter);
  }

  getCurrentfilter() {
    return this.filterObject;
  }

}

此服务允许您设置数据(使用setFilter函数)并订阅此数据。 要订阅过滤器,您可以执行以下操作:

this.filterService.filter.subscribe(newFilter => {
  // do something
});

答案 1 :(得分:0)

您可以使用以下内容:

    private _privateLessonsUrl: string = "http://localhost:3000/api/";
    public privateLessons: any[];

    // call this on each component you need the data
    getPrivateLessonsData() : Observable<any> {
      return new Observable.Of(this.privateLessons);
    }

    // call this on App init
    requestPrivateLessons() : any {
      return this._http.get(this._privateLessonsUrl)
        .map( (response: Response) => response.json() );    
    }

答案 2 :(得分:0)

您的组件会在不知道数据是否来自API的情况下订阅getPrivateLessons()。在服务中,您只需检查privateLessons是否有值,如果有,则返回Observable,否则执行请求。因此,您的组件代码保持不变,只修改您的服务:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';

// ...

public privateLessons: any[];

getPrivateLessons() : any {
  // check if privateLessons has value, if so return the array
  if(this.privateLessons && this.privateLessons.length) {
    return Observable.of(this.privateLessons)
  }
  // privateLessons has no value, perform http-request
  return this._http.get(this._privateLessonsUrl)
    .map((response: Response) => response.json())
    // side effect, store data in local variable
    .do(data => this.privateLessons = data);    
}