Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular 8使用ngIf和异步管道显示和隐藏HTML元素_Javascript_Html_Angular_Typescript_Observable - Fatal编程技术网

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

Javascript Angular 8使用ngIf和异步管道显示和隐藏HTML元素,javascript,html,angular,typescript,observable,Javascript,Html,Angular,Typescript,Observable,我试图根据服务结果显示和隐藏HTML元素。我使用的是*ngIf=“messageService.getData()| async”,但它无法显示或隐藏元素。我使用的是异步,否则“失败消息”会显示一小段时间,然后显示“成功消息” 我有两个这样的标签: <div *ngIf="messageService.getData() | async">Successful Message</div> <div *ngIf="!messageService.getData() |

我试图根据服务结果显示和隐藏HTML元素。我使用的是
*ngIf=“messageService.getData()| async”
,但它无法显示或隐藏元素。我使用的是异步,否则“失败消息”会显示一小段时间,然后显示“成功消息”

我有两个这样的标签:

<div *ngIf="messageService.getData() | async">Successful Message</div>
<div *ngIf="!messageService.getData() | async">Failure Message</div>
以下是源代码:

在您的服务中:

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();
      })
    );
  }
}
导出类MessageComponent实现OnInit{
isServiceAPIWorking:布尔值;
待办事项;
loadingError$=新主题();
构造函数(私有消息服务:消息服务){}
恩戈尼尼特(){
this.todos=this.messageService.getData().pipe(
catchError((错误)=>{
//在这里记录错误是很重要的。
//否则,您将不会在控制台中看到错误。
console.error('加载用户列表时出错',错误);
this.loadingError$.next(true);
返回();
})
);
}
}
在html中:

<div>Show Message:</div>
<div *ngIf="todos | async">Successfull Message</div>
<div *ngIf="loadingError$ | async">Failure Message</div>
显示消息:
成功消息
故障信息

DEMO既然可以在组件中分配数据,为什么还要使用异步管道呢

// 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;
        })
  }
}

这是对
async
管道的错误使用,不是在语法上,而是在语义上。每次触发更改检测时,您都会发出HTTP请求

您可以为HTTP请求存储两个标志(布尔变量)或一个布尔变量,为响应存储一个变量,而不是使用
async
pipe进行检查

下面的示例使用两个标志

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>

成功消息
故障信息

如果你不使用异步,“失败消息”会显示一小段时间,然后显示“成功消息”。是的,当然,我只是调整了你的逻辑,但你可以做更聪明的事情来做你想做的。我明白你的意思,但如果你不使用异步,“失败消息”会在页面加载上显示一小段时间。嗯。。交换
isLoaded
hasrerror
的分配是否有效?更新了答案Well done@Fateme这是我看到的最好的答案,当我遇到这样的问题时我也会这么做。@FatemeFazli我试图看到“失败消息”,但它给出的是可观察的。抛出不是函数错误。我把它改成了“投掷者”,但它仍然没有显示出来。
// message.service.ts

public getData() {
  return this.http.get("https://jsonplaceholder.typicode.com/todos/1")
  .pipe(
    tap((response) => {
      console.log("success");
    }),
    catchError(this.handleError)
  )
}
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>