inv*_*vot 1 class ecmascript-6 angular angular-httpclient
我正在尝试在 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})
}
};
Run Code Online (Sandbox Code Playgroud)
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/')
}
}
Run Code Online (Sandbox Code Playgroud)
你HttpClient的没有定义。在private http: HttpClient;你声明它的代码行中,但永远不要给它一个值,所以它保持为undefined.
这个HttpClient类是Injectable,所以我们可以ApiService像这样将它注入到构造函数中:
constructor(private http: HttpClient) {}
Run Code Online (Sandbox Code Playgroud)
现在我们可以通过调用在这个服务的任何地方访问它 this.http.get(someUrl).subscribe(ex => {});
| 归档时间: |
|
| 查看次数: |
3949 次 |
| 最近记录: |