Angular 通过http使用API

Angular 通过http使用API,angular,Angular,有三种使用API资源的方法,三种方法,可以解决这种情况。 除此之外,我真的不知道这3种方法中的每一种在什么情况下使用。 然而,下面是三个例子

有三种使用API资源的方法,三种方法,可以解决这种情况。
除此之外,我真的不知道这3种方法中的每一种在什么情况下使用。 然而,下面是三个例子<如有需要,我们需要遵循这种方法吗

第一种方法:
它正在创建一个可观察的
this.articles$=this.http.get(this.\u articlesUrl)
然后我们制作
*ngIf=“!(articles$| async)”
然后
*ngFor=“let item of articles$| async;trabcedby:trackElement”

下一步是
*ngIf=“!articles”
然后
*ngFor=“let item of articles;trabckedBy:trackElement”
来解析文章。

它们都没有问题

首先,最佳和常见的做法是将HTTP相关代码放在服务中,而不是直接放在组件中。这使得组件的代码更简单,更容易测试

第一个:你没有说为什么要在服务中使用
share()
。我认为这是因为您注意到在视图中两次使用异步管道会发送两个http请求。但这不是服务的工作,以照顾固定您的观点,所以你不应该这样做

第二个:您似乎不理解
map()
操作符的作用。它只是将可观测源发出的事件转换为其他事件。在本例中,它将形式为
{articles:[…]}
的对象转换为
[…]
。它根本不共享可观察到的东西。如果服务发回一个对象,而您只对该对象的articles数组感兴趣,那么您需要这样做。由于在视图中使用了两次异步,因此将发送两次http请求,这不是您想要做的事情

第三个:这是正确的,但是在destroy上存储订阅和取消订阅通常是无用的:一旦响应返回,observative就完成了,当它完成(或出错)时,订阅方会自动取消订阅。如果您订阅了一个非常长时间运行的可观察对象(比如一个从未完成的间隔),那么这将非常有用

因此,我将使用第三个,但删除不必要的代码

如果确实要使用异步管道,请确保在视图中使用一次且仅使用一次:

<div *ngIf="articles$ | async as articles; else loading">
  Here's the list of articles:
  <div *ngFor="let article of articles"> ... </div>
</div>
<ng-template #loading>
  Loading articles...
</ng-template>

以下是文章列表:
... 
正在加载文章。。。

@Ahmedbhs,当你有一个可观察的

1.-使用| async在.html中使用direct

<div *ngFor="let item of articles$ | async;>...</div>

articles$:Observable<any>  //<--declare your variable
this.articles$=this.httpClient.get("your url")
。。。
第条数据:任何[]//本条款(SDATA)
请确保您订阅了this.httpClient(一个可观察的对象),并且当您得到结果(进入函数subscribe)时,您等于一个变量“this.articlesData”作为调用的结果。所以你迭代一个数据数组

当您订阅数据时,是“良好做法”取消订阅。在第一个示例中,管道异步为您创建。在第二个示例中,您可以使用一个为true且在ngOnAfter中等于false的变量

articlesData:any[];  //<--declare your variable
live:boolean=true;   //<---declare a variable "live"
this.httpClient.get("your url").pipe(
      takeWhile(()=>this.live==true)
      ).subscribe(res=>this.articlesData) 

ngOnAfterInit()
{
    this.live=false;
}
articlesData:any[]//本条款(SDATA)
ngOnAfterInit()
{
这个。活=假;
}

请为您的示例添加ts代码,它应该是这样的:
ngOnInit(){this.articles$=this.http.get(this.\u articlesUrl);}
?如果您正在查看将返回文章的服务代码,假设服务器确实返回了文章数组,它将
返回this.http.get通常它将返回一个可观察的而不是一个文章数组!!!为什么要添加,原因在我链接的文档中解释。如果你想学习如何使用http,请阅读http指南。关于第三种方法,请看我从这里得到的例子:这就是他们推荐的
<div *ngIf="articles$ | async as articles; else loading">
  Here's the list of articles:
  <div *ngFor="let article of articles"> ... </div>
</div>
<ng-template #loading>
  Loading articles...
</ng-template>
<div *ngFor="let item of articles$ | async;>...</div>

articles$:Observable<any>  //<--declare your variable
this.articles$=this.httpClient.get("your url")
<div *ngFor="let item of articlesData>...</div>

articlesData:any[];  //<--declare your variable
this.httpClient.get("your url").subscribe(res=>this.articlesData)
articlesData:any[];  //<--declare your variable
live:boolean=true;   //<---declare a variable "live"
this.httpClient.get("your url").pipe(
      takeWhile(()=>this.live==true)
      ).subscribe(res=>this.articlesData) 

ngOnAfterInit()
{
    this.live=false;
}