3 回答

TA貢獻(xiàn)1824條經(jīng)驗 獲得超6個贊
在您的服務(wù)中:
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>

TA貢獻(xiàn)1802條經(jīng)驗 獲得超10個贊
這是一種錯誤的async管道用法,不是在語法上而是在語義上。每次觸發(fā)更改檢測時,您都會發(fā)出 HTTP 請求。
async您可以存儲兩個標(biāo)志(布爾變量)或一個用于 HTTP 請求的布爾變量和一個用于響應(yīng)的變量,而不是使用管道檢查。
下面的示例使用兩個標(biāo)志。
export class MessageService {
isLoaded = false;
hasError = false;
constructor(private http: HttpClient) { }
public getData() {
this.isLoaded = false;
this.http.get("https://jsonplaceholder.typicode.com/todos/1")
.subscribe(
(response) => {
this.hasError = false;
this.isLoaded = true;
},
(error) => {
this.hasError = true;
this.isLoaded = true;
},
)
}
}
在模板中:
<ng-container *ngIf="isLoaded">
<div *ngIf="!hasError">Successfull Message</div>
<div *ngIf="hasError">Failure Message</div>
</ng-container>

TA貢獻(xiàn)1817條經(jīng)驗 獲得超14個贊
當(dāng)您可以只在組件中分配數(shù)據(jù)時,為什么還要使用異步管道呢?
// message.component.ts
class MessageComponent implements OnInit {
isServiceAPIWorking: boolean;
data: any;
constructor(private messageService: MessageService) { }
ngOnInit() {
this.messageService.getData()
.subscribe(response => {
this.isServiceAPIWorking = true;
// Assign the data
this.data = response;
},
error => {
this.isServiceAPIWorking = false;
})
}
}
// message.component.html
<div>Show Message:</div>
<div *ngIf="data">Successfull Message</div>
<div *ngIf="!data">Failure Message</div>
您的服務(wù)存在錯誤。如果你map不返回任何東西就使用,你最終不會得到任何數(shù)據(jù)。tap如果要進(jìn)行日志記錄,請使用:
// message.service.ts
public getData() {
return this.http.get("https://jsonplaceholder.typicode.com/todos/1")
.pipe(
tap((response) => {
console.log("success");
}),
catchError(this.handleError)
)
}
添加回答
舉報