[英]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. UPDATE:对不起,我抄我的代码错版:我没叫
then
里面的服务像现在所示。
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 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: 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);
}
}
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: 但是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
You need to call the then
method on the returned promise by the getData
method to be able to receive the data: 您需要通过
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);
}
});
}
The then
method must be used within the component and not in the service. then
方法必须在组件而不是服务中使用。
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: 我认为您在
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 {
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
... 其中
(serviceName)
应该是您不可删除的服务的文件名,而导致您在构造函数中将其作为DataService
合并了,它实际上称为RBACService
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.