【问题标题】:Keep HttpRequest value in the component将 HttpRequest 值保留在组件中
【发布时间】:2019-01-10 19:14:29
【问题描述】:

我对 Http Request 值有疑问。我对 Express API 休息做了一个 Http 请求,我想查看整个组件的值。我可以在 observable 上获得数据,但不能在组件的其他功能中获得数据。你能解释一下为什么吗?

import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';


export class UserModel {
  constructor (
    public id: string,
    public name: string,
    public type: string
  ) {}
}


@Injectable()
export class AskingService {

  BASE_URL = 'http://localhost:4201/';

  constructor(private http: HttpClient) { }

    // Get users from EXPRESS API REST
    getUserFromBdd() {
       return  this.http.get<UserModel[]>(this.BASE_URL + 'api/fields');
      }
}

@Component({
  selector: 'app-asking-problem',
  template: `

`
})
export class AskingProblemComponent implements OnInit {

  constructor( private service: AskingService) { }

users;

  ngOnInit() {
    // subscribing to the service
this.service.getUserFromBdd().subscribe(data => {this.users = data, console.log('this.users =', this.users); });
// console return data


console.log('this.users =', this.users);
// console return undefined

  }

}

【问题讨论】:

  • 您在箭头函数中使用逗号运算符,它返回 rightmost 值(undefinedconsole.log 返回)。此外,您还记录了 outside 回调,无论如何都无法设置该值; observables 处理异步代码)。

标签: angular typescript httprequest observable


【解决方案1】:

这很简单。订阅内部调用的操作将在外部调用“console.log('this.users =', this.users)”之后执行,因为一个是同步的,另一个是异步的。

您的对象用户将具有正确的值,但在 http 解析并发出将由订阅函数接收的值之后。明白了吗?

来自Angular Guide on Observables

可观察的

Observables 支持在发布者之间传递消息 和您的应用程序中的订阅者。 Observables 提供了显着的 优于其他事件处理技术,异步 编程,并处理多个值。

【讨论】:

  • 谢谢!我怀疑有类似的事情,但没有找到任何相关信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多