Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment.
For instance: if the environment is set to dev, then the userURL
value should be http://mydomain-dev.com/users/
with devHttpOptions as headers. Similarly, for QA - the userURL
would be http://mydomain-qa.com/users/
with qaHttpOptions
as headers, and so forth.
In order to achieve this, I have implemented a switch case statement that determines which url and header should be assigned based on the specified environment.
However, when attempting to pass this.httpOptions
in the get method -
this.http.get<User[]>(this.userURL, this.httpOptions)
, I encountered a compile time error:
Type 'Observable<HttpEvent<User[]>>' is not assignable to type 'Observable<User[]>'.
Type 'HttpEvent<User[]>' is not assignable to type 'User[]'.
Type 'HttpSentEvent' is missing the following properties from type 'User[]': length, pop, push, concat, and more...
Here is the code snippet:
UserService.ts
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { User } from "./user";
import { HttpHeaders } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) { }
userURL: any;
httpOptions: any;
devHttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('dev-xxxx:yyyy')
})
};
qaHttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('qa-xxxx:yyyy')
})
};
prodHttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('prod-xxxx:yyyy')
})
};
getUsers(environment): Observable<User[]> {
console.log(environment);
switch (environment) {
case 'dev':
this.userURL = 'http://mydomain-dev.com/users/';
this.httpOptions = this.devHttpOptions;
break;
case 'qa':
this.userURL = 'http://mydomain-qa.com/users/';
this.httpOptions = this.qaHttpOptions;
break;
case 'prod':
this.userURL = 'http://mydomain-prod.com/users/';
this.httpOptions = this.prodHttpOptions;
break;
}
return this.http.get<User[]>(this.userURL, this.httpOptions);
}
}
If you could provide assistance with resolving this issue, it would be greatly appreciated! Thank you in advance!