【发布时间】:2018-09-27 02:26:32
【问题描述】:
我正在使用独立的 TypeScript 类调用我的后端服务。在实例化我的共享类的实例时,我能够console.log 捕获的数据。但是,我无法在我的 Angular 组件中访问该类的本地属性和方法。
这是我的组件:
import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../shared/projectService';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
projects: any;
windowWidth: number;
service: ProjectService;
constructor(private httpClient: HttpClient) {
this.service = new ProjectService(this.httpClient);
// returns as undefined
console.log(this.service.getAllProjects());
}
ngOnInit() {
this.windowWidth = window.innerWidth;
}
}
这是我的共享类模块:
import { HttpClient } from '@angular/common/http';
interface Project {
demoURL: string,
githubURL: string,
imgFileName: string,
name: string,
stack: Array<string>
}
export class ProjectService {
private configURL = `https://someURL.herokuapp.com/getAllProjects`;
projects: any;
constructor(private httpClient: HttpClient) {
this.httpClient.get(this.configURL).subscribe(resp => {
this.projects = resp;
});
}
getAllProjects() {
return this.projects;
}
}
如你所见,
我想使用this.service.getAllProjects() 在我的ng 组件中填充我的局部变量projects。当我尝试记录来自共享类ProjectService 的响应时,函数响应为undefined。
当我在使用new 初始化类之后在ProjectService 构造函数中console.log 时,我可以看到我的类能够捕获响应。
为什么要这样做?还有,怎么解决?
谢谢大家。
【问题讨论】:
标签: typescript angular6 angular-httpclient typescript-class