我正在尝试根据服务结果显示和隐藏 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);
}
}
最佳答案
在您的服务中:
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/