已更新
所以我在 preCheckService 中创建一个名为 getData 的函数,我想从其他组件调用它。但由于某种原因,我无法调用该函数,如何使 getData 成为公共(public)函数,以便可以从组件调用它
预检查.service.ts
import {Component,Injectable} from '@angular/core'
import {HttpModule, Http} from "@angular/http";
import 'rxjs/add/operator/map'
import Util from './Util';
@Injectable()
export class preCheckService{
u:Util;
mode:string="local";
constructor(private http: Http ){
this.u = new Util();
}
getData(){
var u =this.u.getPreCheckDefinitions(this.mode);
return u();
}
}
Util.ts
import {Injectable} from '@angular/core'
import {HttpModule, Http} from "@angular/http";
import {subscribeOn} from "rxjs/operator/subscribeOn";
export default class Util{
constructor(private http: Http){
}
getPreCheckDefinitions = type =>{
switch (type){
case 'server':
return function getData(){
return this.http.post("server/PreCheck/preCheckDefs.do", {radBusLine : 1}).map(
(res) => res.json()
)
};
case 'local':
return function getData(){
return this.http.get("app/data/preCheckData.json").map(
(res) => res.json()
)
};
}
};
}
我遇到了以下错误
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'http' of undefined
TypeError: Cannot read property 'http' of undefined
最佳答案
为什么不让 getData 成为你服务的一个方法呢?
@Injectable()
export class preCheckService{
u:Util;
mode:string="dev";
constructor(private http: Http ){
this.u = new Util();
this.initialize();
}
getData(){
return this.u.getPreCheckDefinitions(this.mode);
}
}
或者您的 getPreCheckDefinition 可能会像下面这样进行更改。否则在调用时将不知道“this”
getPreCheckDefinitions(type){
switch (type){
case 'server':
return this.http.post("server/PreCheck/preCheckDefs.do", {radBusLine : 1}).map(
(res) => res.json()
);
case 'local':
return this.http.get("app/data/preCheckData.json").map(
(res) => res.json()
);
}
}
这样 getPreCheckDefinitions 将返回一个可观察值。
关于javascript - 使用函数柯里化(Currying)在 typescript 中构建实用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42655748/