在Angular http方法的函数外部分配响应值

问题描述

user.component.ts


ngOnInit(): void
  {
    var data;
    this.auth=this.cookie.get("auth");
    this.servicefetch.ContactList(this.auth).subscribe
    (
      (response)=>
      {
        data=response;
      },(error)=>{console.log(error)}

    );
  }

serviceCRUD.service.ts

 ContactList(auth:String)
 {
    const headers = { "content-type": "application/json","Authorization": "Contacts " + auth };

    return this.http.get<any>('http://localhost:8080/contacts',{headers});
 }

在这里,我想将响应分配给其他变量,例如data。但是,当我打印出数据时,却无法确定。我认为是因为这是异步的。我可以通过任何方式将其分配给变量数据

解决方法

您必须在Component类的范围内声明状态变量。

export default App extends Component {

data: any;

ngOnInit(): void
  {
    this.auth=this.cookie.get("auth");
    this.servicefetch.ContactList(this.auth).subscribe
    (
      (response)=>
      {
        this.data=response;
       // call the next callback (store the token or go to next route)
      },(error)=>{console.log(error)}
    );
  }
}

您可以像这样签入模板:

<div *ngIf="data">
    data.yourProperty
</div>
,

您已经说过,http调用是异步操作。

如果我们尝试以下操作

let data;
this.servicefetch.ContactList(this.auth).subscribe({
  next: response => data = response
});
console.log(data);

数据将是不确定的,因为此代码是在响应返回之前执行的。

角度而言,处理上述问题的最好方法是将observable分配给下面的示例变量

  myData$ = this.servicefetch.ContactList(this.auth);

现在在模板和各种操作中,您可以使用此可观察的对象。例如在您可能拥有的模板中显示数据

  <ng-container *ngIf='myData$ | async as data'>
    // data is now available here
  </ng-container>

在您的TS文件中,您可以订阅此变量并执行其他操作

  myData$.subscribe({ next: (data) => console.log(data)})