猿问

Angular 8 使用 ngIf 和异步管道来显示和隐藏 HTML 元素

我正在尝试根据服务结果显示和隐藏 HTML 元素。我正在使用,*ngIf="messageService.getData() | async"但无法显示或隐藏元素。我正在使用异步,否则会在短时间内显示“失败消息”,然后显示“成功消息”。


我有 2 个这样的标签:


<div *ngIf="messageService.getData() | async">Successful Message</div>

<div *ngIf="!messageService.getData() | async">Failure Message</div>

在服务中,我有一个这样的代码:


export class MessageService {

  constructor(private http: HttpClient) { }


  public getData() {

    return this.http.get("https://jsonplaceholder.typicode.com/todos/1")

    .pipe(

      map((response) => {

        console.log("success");

      }),

      catchError(this.handleError)

    )

  }


  private handleError(error: Response) {

    console.log("handleError")

    let errMsg: string;

    errMsg = "error"

    return Observable.throw(errMsg);

  }

}


慕桂英546537
浏览 290回答 3
3回答

慕妹3242003

在您的服务中:public getData() {&nbsp; &nbsp; return this.http.get("https://jsonplaceholder.typicode.com/todos/1")&nbsp; &nbsp; .pipe(&nbsp; &nbsp; &nbsp; map((response) => {&nbsp; &nbsp; &nbsp; &nbsp; return response; // return res&nbsp; &nbsp; &nbsp; }),&nbsp; &nbsp; &nbsp; catchError(this.handleError)&nbsp; &nbsp; )&nbsp; }在您的组件中:export class MessageComponent implements OnInit {&nbsp; isServiceAPIWorking: boolean;&nbsp; todos;&nbsp; loadingError$ = new Subject<boolean>();&nbsp; constructor(private messageService: MessageService) { }&nbsp; ngOnInit() {&nbsp; &nbsp; this.todos = this.messageService.getData().pipe(&nbsp; &nbsp; &nbsp; catchError((error) => {&nbsp; &nbsp; &nbsp; &nbsp; // it's important that we log an error here.&nbsp; &nbsp; &nbsp; &nbsp; // Otherwise you won't see an error in the console.&nbsp; &nbsp; &nbsp; &nbsp; console.error('error loading the list of users', error);&nbsp; &nbsp; &nbsp; &nbsp; this.loadingError$.next(true);&nbsp; &nbsp; &nbsp; &nbsp; return of();&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; );&nbsp; }}在你的 html 中:<div>Show Message:</div><div *ngIf="todos | async">Successfull Message</div><div *ngIf="loadingError$ | async">Failure Message</div>

守候你守候我

这是一种错误的async管道用法,不是在语法上而是在语义上。每次触发更改检测时,您都会发出 HTTP 请求。async您可以存储两个标志(布尔变量)或一个用于 HTTP 请求的布尔变量和一个用于响应的变量,而不是使用管道检查。下面的示例使用两个标志。export class MessageService {&nbsp; isLoaded = false;&nbsp; hasError&nbsp; = false;&nbsp; constructor(private http: HttpClient) { }&nbsp; public getData() {&nbsp; &nbsp; this.isLoaded = false;&nbsp; &nbsp; this.http.get("https://jsonplaceholder.typicode.com/todos/1")&nbsp; &nbsp; .subscribe(&nbsp; &nbsp; &nbsp; &nbsp;(response) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.hasError = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.isLoaded = true;&nbsp; &nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; &nbsp; &nbsp;(error) => {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.hasError = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.isLoaded = true;&nbsp; &nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; )&nbsp; }}在模板中:<ng-container *ngIf="isLoaded">&nbsp; &nbsp; <div *ngIf="!hasError">Successfull Message</div>&nbsp; &nbsp; <div *ngIf="hasError">Failure Message</div></ng-container>

大话西游666

当您可以只在组件中分配数据时,为什么还要使用异步管道呢?// message.component.tsclass MessageComponent implements OnInit {&nbsp; isServiceAPIWorking: boolean;&nbsp; data: any;&nbsp; constructor(private messageService: MessageService) { }&nbsp; ngOnInit() {&nbsp; &nbsp; this.messageService.getData()&nbsp; &nbsp; &nbsp; .subscribe(response => {&nbsp; &nbsp; &nbsp; &nbsp; this.isServiceAPIWorking = true;&nbsp; &nbsp; &nbsp; &nbsp; // Assign the data&nbsp; &nbsp; &nbsp; &nbsp; this.data = response;&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.isServiceAPIWorking = false;&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; }}// message.component.html<div>Show Message:</div><div *ngIf="data">Successfull Message</div><div *ngIf="!data">Failure Message</div>您的服务存在错误。如果你map不返回任何东西就使用,你最终不会得到任何数据。tap如果要进行日志记录,请使用:// message.service.tspublic getData() {&nbsp; return this.http.get("https://jsonplaceholder.typicode.com/todos/1")&nbsp; .pipe(&nbsp; &nbsp; tap((response) => {&nbsp; &nbsp; &nbsp; console.log("success");&nbsp; &nbsp; }),&nbsp; &nbsp; catchError(this.handleError)&nbsp; )}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答