我试图在Angular 7中创建一个简单的API服务,可以将其包含在任何需要它的组件中。但是,每当我从组件调用它时,都会出现错误。例如,如果从组件内部调用ApiService.read('/public/flavorsofcandy/')
,则会得到:
ERROR TypeError: Cannot read property 'get' of undefined
现在,我不确定为什么会这样,但是我觉得这很简单而且很愚蠢。但是,我无处发现为什么会这样。我觉得这是由于我没有完全理解与类和诸如此类有关的概念,而不是Angular 7本身。
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ApiService {
private baseUrl = "http://localhost:11000/";
private http: HttpClient;
public create = (req:string, options?:any) => {
this.http.post(this.baseUrl+req, options)
.subscribe(response=> {return response})
}
public read = (req:string, options?:any) => {
this.http.get(this.baseUrl+req,options)
.subscribe(response=> {return response})
}
public update = (req:string, options?:any) => {
this.http.put(this.baseUrl+req, options)
.subscribe(response=> {return response})
}
public delete = (req:string, options?:any) => {
this.http.delete(this.baseUrl+req, options)
.subscribe(response=> {return response})
}
};
mycomponent.ts
import { Component, OnInit } from '@angular/core';
import { ApiService as api} from '../../scripts/api.service';
@Component({
selector: 'MyComponent ',
templateUrl: './MyComponent.html',
styleUrls: ['./MyComponent.scss'],
})
export class MyComponent implements OnInit {
public flavorsList: any;
constructor() { }
ngOnInit() {
this.getFlavors()
}
getFlavors() {
this.flavorsList = api.read('/public/flavorsofcandy/')
}
}
答案 0 :(得分:3)
您的HttpClient
未定义。在代码行private http: HttpClient;
中声明了它,但从未给它赋值,所以它仍为undefined
。
HttpClient
类是 Injectable ,因此我们可以将其注入到ApiService
的构造器中,如下所示:
constructor(private http: HttpClient) {}
现在我们可以通过调用this.http.get(someUrl).subscribe(ex => {});
答案 1 :(得分:3)
您没有注入HttpClient
。您需要使用constructor
进行注入。参见https://angular.io/guide/dependency-injection。不要忘记在您的HttpClientModule
中导入AppModule
。