I am now working with Angular 4. I have not found any proper solution about method overloading in Angular 2 or 4. Is it possible to implement method overloading in an angular service class? Or I am interested to know details about it. Thanks in advance.
I have just tried to crate Service like below but found Duplicate 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);
}
}
Function overloading is a mechanism or ability to create multiple methods with the same name but different parameter types and return type. However, it can have the same number of parameters. Function overloading is also known as method overloading.
TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program.
Instead of overloading methods, make the token parameter optional.
postCall(url, data, token?) { // with three parameters
return resultFromServer;
}
Hope it helps
As of TypeScript 1.4, you can typically remove the need for an overload using an optional parameter and union type(if you don't know the type of the param). The above example can be better expressed using:
postCall(url: string, data: Object, token?: string | number) {
return resultFromServer;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With