Method overloading in Angular 4/2
I am now working with Angular 4. I have not found the correct solution for method overloading in Angular 2 or 4. Is it possible to implement method overloading in an Angular service class? Or I'm curious to know the details about this. Thanks in advance.
I just tried to compile the Service as shown below but found Dublicate Function Implementation Error
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;}
}
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);
}
}
+3
Amir
source
to share
2 answers
Instead of overloading methods, make an optional token parameter .
postCall(url, data, token?) { // with three parameters
return resultFromServer;
}
Hope it helps
+9
Jayakrishnan gounder
source
to share
As with TypeScript 1.4, you can usually remove the need for overloading by using an optional parameter and union type (if you don't know the type of the parameter). The above example could be better expressed with:
postCall(url: string, data: Object, token?: string | number) {
return resultFromServer;
}
+3
monica
source
to share