简体   繁体   中英

Transferring data from service.ts to component

I am really stuck in this problem, hopefully I can get some help here.

Basically, I am doing a simple get http request in http.service and then transferring the json object to the filter.service. After that I want to carry the output array into component. But I get an empty error.

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()

}
}

You could think of returning promise from setData function as soon as this.dataArr object gets filled up.

Code

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
         }
      );
   }
}

You should be waiting till setData method ajax to be completed by putting then call on promise.

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

you are using an asynchronous function setData so you have to wait until until the observable resolves:

try this

filtering.service

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.
      }
  )
}


}

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.getData().subscribe((items)=>{
      this.items = items;
   });
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM