Ami*_*mir 6 typescript angular
我现在正在使用Angular 4.我没有在Angular 2或4中找到任何关于方法重载的正确解决方案.是否有可能在角度服务类中实现方法重载?或者我有兴趣知道它的细节.提前致谢.
我刚刚尝试像下面那样创建服务但发现Dublicate函数实现错误
ApiService.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class ApiService {
constructor() { }
postCall(url, data, token) { // with three parameters
return resultFromServer; }
postCall(url, data) { // with two parameters
return resultFromServer;}
}
Run Code Online (Sandbox Code Playgroud)
AuthenticationService.ts:
import { Injectable } from '@angular/core';
import { ApiService } from "app/_services/api.service";
import FunUtils from "app/_helper/utils";
@Injectable()
export class AuthenticationService {
constructor(private api: ApiService) { }
rest_login_call(userName, password) {
let data = { username: userName, password: password };
let url = "http://localhost:8000";
return this.api.postCall(url, data);
}
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*der 13
而不是重载方法,使令牌参数可选.
postCall(url, data, token?) { // with three parameters
return resultFromServer;
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
从 TypeScript 1.4 开始,您通常可以使用可选参数和联合类型(如果您不知道参数的类型)来消除对重载的需要。上面的例子可以更好地表达:
postCall(url: string, data: Object, token?: string | number) {
return resultFromServer;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5939 次 |
| 最近记录: |