为什么 Subscribe 在 Angular 中没有 Observable 的情况下工作
Why Subscribe is working without Observable in Angular
我想了解 Angular 和 HttpClient
的一些基础知识。我的代码正在运行,但我不明白如何运行。我检查了这两个链接:
- How to declare Return Types for Functions in TypeScript
我在 YouTube 上看过这个视频:
我了解到 HttpClient
的 GET 方法的语法是:
get(url: string, options: {...}): Observable<any>
所以我按照视频中的要求做了。这是我的案例 1:
用户服务
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
}
}
为什么 VSCode 抱怨:
Value of type 'typeof Observable' is not callable. Did you mean to include 'new'?
事实上,即使我根本不指定 Observable
,我的代码也能完美运行。这是案例 2:
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users");
}
}
这是我的组件(对于这两种情况):
用户列表
users=[];
constructor(private userService: UserService) { }
ngOnInit() {
this.fetchAllUsers();
}
fetchAllUsers() {
this.userService.getAllEUsers().subscribe(
res => {
this.users.push(res)
}
);
}
请指出我在这两种情况下的错误。我想我在某处违反了 Angular 规则。
PS:youtube教程截图:
下一行是您代码中的无效语句:
return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
我认为您正在尝试为此处的方法指定一个 return 值,在这种情况下,您需要像这样更改方法声明:
getAllUsers(): Observable<any> {
return this._http.get("https://jsonplaceholder.typicode.com/users");
}
您可能想参加 TypeScript 复习课程 here。
我想了解 Angular 和 HttpClient
的一些基础知识。我的代码正在运行,但我不明白如何运行。我检查了这两个链接:
- How to declare Return Types for Functions in TypeScript
我在 YouTube 上看过这个视频:
我了解到 HttpClient
的 GET 方法的语法是:
get(url: string, options: {...}): Observable<any>
所以我按照视频中的要求做了。这是我的案例 1:
用户服务
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
}
}
为什么 VSCode 抱怨:
Value of type 'typeof Observable' is not callable. Did you mean to include 'new'?
事实上,即使我根本不指定 Observable
,我的代码也能完美运行。这是案例 2:
...
export class UserService {
constructor(private _http: HttpClient) { }
getAllUsers() {
return this._http.get("https://jsonplaceholder.typicode.com/users");
}
}
这是我的组件(对于这两种情况):
用户列表
users=[];
constructor(private userService: UserService) { }
ngOnInit() {
this.fetchAllUsers();
}
fetchAllUsers() {
this.userService.getAllEUsers().subscribe(
res => {
this.users.push(res)
}
);
}
请指出我在这两种情况下的错误。我想我在某处违反了 Angular 规则。
PS:youtube教程截图:
下一行是您代码中的无效语句:
return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
我认为您正在尝试为此处的方法指定一个 return 值,在这种情况下,您需要像这样更改方法声明:
getAllUsers(): Observable<any> {
return this._http.get("https://jsonplaceholder.typicode.com/users");
}
您可能想参加 TypeScript 复习课程 here。