首页 > 解决方案 > 在Angular http方法中分配函数外的响应值

问题描述

用户.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)}

    );
  }

服务CRUD.service.ts

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

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

在这里,我想将响应分配给另一个变量说数据。但是当我打印出数据时,我得到了不确定。我认为这是因为这是异步的。任何方式我都可以将它分配给变量数据

标签: angularajaxangular-materialangular-services

解决方案


您必须在 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>

推荐阅读