我正在使用独立的 TypeScript 类调用我的后端服务。console.log
在实例化我的共享类的实例时,我能够捕获数据。但是,我无法在我的角度组件中访问该类的本地属性和方法。
这是我的组件:
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;
}
}
如你看到的,
我想projects
在我的 ng 组件中使用this.service.getAllProjects()
. 当我尝试记录来自共享类ProjectService
的响应时,函数响应是undefined
.
当我在使用初始化类之后console.log
进入ProjectService
构造函数时,new
我可以看到我的类能够捕获响应。
为什么要这样做?另外,我该如何解决?
多谢你们。