I wanted to understand some basics of Angular and HttpClient
. My code is working but I don't understand how. I checked these two links:
- How to correctly subscribe Angular HttpClient Observable?
- How to declare Return Types for Functions in TypeScript
I've watched this video on YouTube:
I learnt that the syntax of HttpClient
's GET method is:
get(url: string, options: {...}): Observable<any>
So I did as I was told to do in the video. Here is my case 1:
UserService
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
}
}
Why VSCode is complaining:
Value of type 'typeof Observable' is not callable. Did you mean to include 'new'?
In fact my code works perfectly If I don't even specify Observable
at all. Here is case 2:
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users");
}
}
And here's my component(for both the cases):
UserList
users=[];
constructor(private userService: UserService) { }
ngOnInit() {
this.fetchAllUsers();
}
fetchAllUsers() {
this.userService.getAllEUsers().subscribe(
res => {
this.users.push(res)
}
);
}
Please point out my mistakes in both cases. I think I'm violating Angular rules somewhere.
PS: Screenshot of the youtube tutorial: