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

Assign the response value outside the function in Angular http method

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

这里我想将响应分配给另一个变量 say 数据。但是当我打印出数据时,我得到了未定义的信息。我认为这是因为这是异步的。我可以用任何方式将它分配给变量数据

您必须在组件的 class 范围内声明您的状态变量。

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

数据将是未定义的,因为这段代码是在响应返回之前执行的。

在 angular 中,处理上述问题的最佳方法是将 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)})