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

标签 javascript html angular typescript observable

我正在尝试根据服务结果显示和隐藏 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);
  }
}

这是源代码:https://stackblitz.com/edit/angular-iqr6az

最佳答案

在您的服务中:

public getData() {
    return this.http.get("https://jsonplaceholder.typicode.com/todos/1")
    .pipe(
      map((response) => {
        return response; // return res
      }),
      catchError(this.handleError)
    )
  }

在你的组件中:

export class MessageComponent implements OnInit {
  isServiceAPIWorking: boolean;
  todos;
  loadingError$ = new Subject<boolean>();
  constructor(private messageService: MessageService) { }

  ngOnInit() {
    this.todos = this.messageService.getData().pipe(
      catchError((error) => {
        // it's important that we log an error here.
        // Otherwise you won't see an error in the console.
        console.error('error loading the list of users', error);
        this.loadingError$.next(true);
        return of();
      })
    );
  }
}

在您的 html 中:

<div>Show Message:</div>
<div *ngIf="todos | async">Successfull Message</div>
<div *ngIf="loadingError$ | async">Failure Message</div>

DEMO 🚀🚀 .

关于javascript - Angular 8 使用 ngIf 和异步管道来显示和隐藏 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58286423/

相关文章:

javascript - 如何将数字分成整数部分,每个部分都是n的倍数?

javascript - 即使 REST 服务器设置 header ,访问控制允许来源错误

html - 一个 div 在另一个之下的问题

javascript - 将作用域从一个函数传递到另一个函数

javascript - 父div的CSS动态图像宽度

python - 用 Beautiful Soup 解析 div 子元素

angular - ionic Angular 平移不起作用

angular - environment.production 变量在 app.module.ts 中始终为真

angular - RXJS 5 .subscribe() 没有参数

javascript - 是否可以在 Map() 中存储自定义对象?