简体   繁体   中英

Angular2 cannot get mock data from Service

UPDATE: sorry i copied the wrong version of my code: i did call then inside the service as shown now.

I'm creating a Service that provides mock data (following a similar structure as here ) but cannot get data for some reason.

snippet from AppComponent

export class AppComponent implements OnInit{
  ngOnInit(){
    this.getData();
  }


  constructor(private _dataService: DataService){ }

  getData(){
      console.log('get data called');
      var data = this._dataService.getData();
      console.log('data type is '+typeof(data));
      console.log('data key is ');
      for(var k in data){
        console.log(k);
      }

DataService is as follows:

import {Injectable} from 'angular2/core';
import {MOCK_DATA} from './mock-data';

@Injectable()
export class DataService{
  getData(){
    return Promise.resolve(MOCK_DATA).then(data => data);
  }
}

mock data is:

export var MOCK_DATA = {
  "apple": [
    {"taste": "apple", "really": false},
    {"taste": "random", "really": true},
  ],
  "orange": [
    {"taste": "orange", "really": false},
    {"taste": "random", "really": true},
  ],
}

however the console.log results are:

get data called
app.component.ts:46 data type object
app.component.ts:47 data key 
app.component.ts:49 __zone_symbol__state
app.component.ts:49 __zone_symbol__value
app.component.ts:49 then
app.component.ts:49 catch

You need to call the then method on the returned promise by the getData method to be able to receive the data:

getData() {
  console.log('get data called');
  this._dataService.getData().then(data => {
    // Handle the data

    // For example
    console.log('data type is '+typeof(data));
    console.log('data key is ');
    for(var k in data){
      console.log(k);
    }
  });
}

The then method must be used within the component and not in the service.

Your service should be:

@Injectable()
export class RBACService{
  getData(){
    return Promise.resolve(MOCK_DATA);
  }
}

instead of

@Injectable()
export class RBACService{
  getData(){
    return Promise.resolve(MOCK_DATA).then(data => data);
  }
}

I think you are missing some important part of your code in the decorator for the AppComponent , something like this:

import { Component, OnInit } from 'angular2/core';
import { RBACService } from './(serviceName).service';

@Component({
    selector: 'my-app',
    template: `whatever...`,
    providers: [RBACService]
})
export class AppComponent implements OnInit {

Where (serviceName) should be the file name of your inyectable service and whatch out cause you inyected it at the constructor as DataService and it's actually called RBACService ...

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