我想将数据从服务返回到组件,但是当我使用服务变量返回数据时,没有出现错误但只是未定义....请指导我完成错误 . 当使用离子相同的逻辑我应用于角度i获得数据但不在角度4应用中 .
signal.service.ts
当我做 console.log(this.signal)
正确地给我一个对象数组 .
import { Injectable } from '@angular/core';
import {HttpModule, Http} from '@angular/http';
@Injectable()
export class SignalsService {
signal : Array<any>;
constructor(public _http:Http) {
this._http.get('http://localhost/4x/data.php')
.subscribe(res =>{
this.signal = res.json().data;
return this.signal
});
}
}
我的组件在这里,当我做console.log信号从服务返回数据时说 Undefined
home.component.ts
import { Component, OnInit } from '@angular/core';
import {HttpModule, Http} from '@angular/http';
import {SignalsService} from '../signals.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
sig :Array<any>;
constructor(public _http:Http,public _signa:SignalsService) {
}
ngOnInit() {
console.log(this._signa.signal);
}
而且
当我直接在ngOnInit部分的home.component.ts中插入HTTP的服务请求时,它工作并返回数据,但为什么我的服务不起作用 .
2 回答
你的服务实现是正确的,但你想在构造函数中加载所有东西更好有一个单独的方法并调用get方法,现在只需将组件中的代码替换为此 .
更多关于services
最好的解决方案是 Service
Component
我有同样的错误 . 我所做的是在ngOnInit中添加订阅,就像上面的@Rahul Singh一样,我在get()中使用map . 像这样:
Component