将数据从service.ts传输到组件

时间:2017-03-26 20:41:00

标签: angular typescript

我真的陷入了这个问题,希望我能在这里得到一些帮助。

基本上,我在http.service中做一个简单的获取http请求,然后将json对象传递给filter.service。之后,我想将输出数组携带到组件中。但我得到一个空的错误。

http.service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class HttpService {

constructor(private http : Http) { }

getData() {
return this.http.get('https://angular2-49133.firebaseio.com/catalog.json')
       .map((response : Response) => response.json());
}

}

filtering.service

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

@Injectable()
export class FilterService {
public dataArr = [];
constructor(private httpService : HttpService) { }

setData() {
this.httpService.getData()
  .subscribe((data) => 
      {
        const resultArr = [];
        for(let key in data) {
          resultArr.push(data[key]);
        }
       this.dataArr = resultArr; //console.log(resultArr) works in component.
      }
  )
}

getData() {
return this.dataArr;
}

}

component.ts

import { Component, OnInit } from '@angular/core';

import { FilterService } from '../../filter.service';

@Component({
selector: 'ubi-item-section',
templateUrl: './item-section.component.html',
styleUrls: ['./item-section.component.css']
})
export class ItemSectionComponent implements OnInit{
items = [];
filter;
constructor(private filterService : FilterService) { }

ngOnInit() {
this.filterService.setData();
this.items = this.filterService.getData()

}
}

2 个答案:

答案 0 :(得分:1)

只要setData对象被填满,您就可以考虑从this.dataArr函数返回承诺。

<强>代码

setData() {
  return new Promise(resolve, reject) {
    this.httpService.getData()
      .subscribe((data) => 
         {
            const resultArr = [];
            for(let key in data) {
              resultArr.push(data[key]);
            }
            this.dataArr = resultArr;
            resolve(this.dataArr); //resolve function will complete promise
         }
      );
   }
}

您应该等待setData方法ajax完成,方法是then调用promise。

this.filterService.setData().then(
   () => this.items = this.filterService.getData()
);

答案 1 :(得分:0)

您正在使用异步函数public RLFDatabaseTableViewModel() { LoadDBInstances(); LoadDBInfoCommand = new RelayCommand(LoadDBInfo); SelectedDBInstance = DBInstances[0]; //selected the first item } ,因此您必须等待 直到观察结果解决:

试试这个

<强> filtering.service

setData

component.ts:

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

@Injectable()
export class FilterService {
public dataArr = [];
constructor(private httpService : HttpService) { }

getData() {
return this.httpService.getData()
  .map((data) => 
      {
        const resultArr = [];
        for(let key in data) {
          resultArr.push(data[key]);
        }
       return resultArr; //console.log(resultArr) works in component.
      }
  )
}


}