I was trying to grasp the basics of Angular and HttpClient
. Surprisingly, my code is actually working, but I'm struggling to comprehend why. In my quest for understanding, I delved into these two insightful links:
- How to properly subscribe to Angular HttpClient Observables?
- How to define Return Types for Functions in TypeScript
A YouTube video also caught my attention:
From what I gathered, the syntax for HttpClient
's GET method appears as follows:
get(url: string, options: {...}): Observable<any>
Hence, following the instructions provided in the video, I implemented it accordingly. Here's my first approach:
UserService
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
}
}
However, VSCode raised an error:
The value of type 'typeof Observable' cannot be called directly. Are you missing the 'new' keyword?
Interestingly, my code functions flawlessly even without explicitly mentioning Observable
. Consider my second scenario:
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users");
}
}
Furthermore, here's the snippet from my component (applicable to both cases):
UserList
users=[];
constructor(private userService: UserService) { }
ngOnInit() {
this.fetchAllUsers();
}
fetchAllUsers() {
this.userService.getAllEUsers().subscribe(
res => {
this.users.push(res)
}
);
}
If you could highlight any mistakes I've made in either case, I would greatly appreciate it. It seems like I might be unintentionally breaking some Angular conventions.
P.S.: Attached a screenshot from the tutorial on YouTube: