我创建了一个服务,假设它调用http请求。我的组件从ngOnInit()调用该函数。由于组件在http获取请求之前完成调用,因此无法在页面上显示数据。
需要帮助。 SERVICE:
import {HttpClientModule} from '@angular/common/http';
import { OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class studentsInfoService implements OnInit
{
_StudentsInfo;
ngOnInit(): void {
}
constructor(private http: HttpClient){};
getStudentsList():Observable<any>{
this.http.get("http://192.168.2.5:81/api/values").subscribe(data=>
{
console.log("Invoked getStudentsList :)");
this._StudentsInfo = data;
console.log(data);
return data;
},err=>{
console.log("error in getStudentsList");
return null;
})
return this._StudentsInfo;
}
}
成分:
import { Component, OnInit } from '@angular/core';
import {studentsInfoService} from '../../Services/studensInfo.service';
@Component({
selector: 'app-students-info',
templateUrl: './students-info.component.html',
styleUrls: ['./students-info.component.css'],
providers:[studentsInfoService]
})
export class StudentsInfoComponent implements OnInit {
_sData=null;
constructor(private sInfoService:studentsInfoService) { }
ngOnInit() {
let x = this.sInfoService.getStudentsList();
x.subscribe(x=> this._sData = x);
}
}
获取错误错误类型错误:无法读取属性&#39;订阅&#39;未定义的 在StudentsInfoComponent.webpackJsonp ... / .. / .. / .. / .. / src / app上 需要帮助才能对服务方法进行同步调用。
谢谢,
答案 0 :(得分:0)
此错误是由于使用了订阅 的 this.http.get( “http://192.168.2.5:81/api/values”)。订阅()强>
在此使用“map”而不是“subscribe”,因此代码将为
return this.http.get("http://192.168.2.5:81/api/values").map(
{
console.log("Invoked getStudentsList :)");
this._StudentsInfo = data;
console.log(data);
return data;
},err=>{
console.log("error in getStudentsList");
return null;
})
)