繁体   English   中英

Angular2无法从Service获取模拟数据

[英]Angular2 cannot get mock data from Service

UPDATE:对不起,我抄我的代码错版:我没叫then里面的服务像现在所示。

我正在创建一个提供模拟数据的服务(遵循与此处类似的结构),但是由于某种原因而无法获取数据。

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如下:

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

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

模拟数据是:

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

但是console.log结果是:

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

您需要通过getData方法在返回的getData上调用then方法,以便能够接收数据:

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

then方法必须在组件而不是服务中使用。

您的服务应为:

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

代替

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

我认为您在AppComponent的装饰器中缺少代码的某些重要部分,如下所示:

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

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

其中(serviceName)应该是您不可删除的服务的文件名,而导致您在构造函数中将其作为DataService 合并了,它实际上称为RBACService ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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