我正在创建一个在初始化时从服务请求数据的组件。
该服务存在于共享模块中,该模块导入到我的新组件所在的功能模块中。
我遇到的问题是,当我打电话给' getControl'方法,我得到一些错误:
无法阅读财产'订阅'未定义的
当我在console.log中时,我可以看到它存在的服务,但是getControl方法返回为undefined。
collection.component.ts
import { Component, OnInit } from '@angular/core';
import { ControlsService } from '../../../shared/services/controls.service'
import { Observable } from 'rxjs';
@Component({
selector: 'app-collection',
templateUrl: './collection.component.html',
styleUrls: ['./collection.component.css'],
})
export class CollectionComponent implements OnInit {
control$:Observable<any>
id:string = "9FC34C22-CB9A-C985-3EAD-33443295AC6C"
constructor(public controlService:ControlsService) { }
ngOnInit() {
console.log(">>CollectionComponent:ngOnInit--")
this.controlService.getControl(this.id).subscribe(res => {this.control$ = res});
}
}
control.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import {BaseService} from './base.service'
@Injectable()
export class ControlsService {
apiUrl = './data/controls.json';
public data:any
constructor(private http: Http) { }
public getData(): Observable<any>
{
console.log(">>BaseService:getData--")
return this.http.get(this.apiUrl)
.map(this.extractData)
.catch(this.handleError);
}
public getControl(controlID:any): Observable<any>
{
console.log(">>ControlsService:getControl--")
if(!this.data)
{
this.getData().subscribe(res => {
this.data = res;
this.getControl(controlID)
}
)
}
else
{
let returnData:Observable<any> = this.data.filter(control => control.id == controlID)
return returnData
}
}
public extractData(res: Response)
{
console.log(">>ControlsService:extractData--")
let body = res.json();
this.data = body.data.control
return this.data || { };
}
private handleError (error: any)
{
console.log(">>BaseService:handleError--")
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
控制台错误也不会显示错误存在于哪个文件中。 如果有人能看一看并告诉我哪里出错了,我将不胜感激。