My journey into angular/ionic app development is just beginning. I came across the following piece of advice recently
Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure.
Currently, I am working on an ionic app where the API services return data to the user. Let's consider a login function scenario where the API service returns data upon login request.
In my Ionic project, I have created a provider through which HTTP calls are made to the API using HTTPClient.
//Provider
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
interface LoginResponse {
success: boolean;
message: string;
token: string;
userId: number;
}
@Injectable()
export class LoginServicesProvider {
constructor(public http: HttpClient) {
}
login(reqData): Observable<LoginResponse[]> {
return this.http.post<LoginResponse[]>('localhost:3000/api/login', reqData);
}
}
By examining the code above, it is evident that I've defined an interface named LoginResponse
Below is the code snippet for the Login component:
//Component
import { LoginServicesProvider } from './../../providers/login-services/login-services';
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'page-login-page',
templateUrl: 'login-page.html',
})
export class LoginPage {
constructor(private loginService: LoginServicesProvider) {
}
onSubmit() {
let reqParams = {
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b7b0b7bdb3b3bbb7bfba96bfb2f8b5b9bb">[email protected]</a>',
password: 'password',
};
this.loginService.login(reqParams).subscribe(res => {
console.log('success');
});
}
}
For now, the example merely logs a message to the console.
Now, here are my queries
1) In accordance with the earlier statement, does my LoginResponse interface effectively validate the incoming data? If not, how and where should I implement such validation- in the provider or the component?
2) Assuming I have multiple interfaces within a single provider, one for login data and another for user profile data, among others, where should I organize them? Can I segregate them into separate files and export them? I haven't come across any specific ionic commands to create interfaces
Thank you! I'm determined to kickstart my career on the right foot and avoid common pitfalls. That's why I decided to seek guidance through this post.