Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

typescript - Why Subscribe is working without Observable in Angular

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:

  1. How to correctly subscribe Angular HttpClient Observable?
  2. How to declare Return Types for Functions in TypeScript

I've watched this video on YouTube:

  1. observable and subscribe in Angular 8 | Angular 8 Tutorial in Hindi

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following line is an invalid statement in your code:

return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;

I think you are trying to specify a return value for the method here, in which case, you need to change the method declaration like this:

getAllUsers(): Observable<any> {
  return this._http.get("https://jsonplaceholder.typicode.com/users");
}

You might want to take a TypeScript refresher course here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...