简体   繁体   English

在组件中保留 HttpRequest 值

[英]Keep HttpRequest value in the component

I have a problem with Http Request value.我有 Http 请求值的问题。 I do an Http request to an Express API rest and I would like to see the value all over the component.我向 Express API rest 发出 Http 请求,我想查看整个组件的值。 I can have the data on the observable but not in other function of my component.我可以在 observable 上获得数据,但不能在我的组件的其他功能中获得数据。 Could you explain me why?你能解释一下为什么吗?

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

  }

}

This is simple.这很简单。 The action called inside the subscribe will execute much after the outside call "console.log('this.users =', this.users)" because one is sync and the other is async.订阅内部调用的操作将在外部调用“console.log('this.users =', this.users)”之后执行,因为一个是同步的,另一个是异步的。

Your object user will have the correct value but just after the http resolve and emit a value that will be received by the subscribed function.您的对象用户将具有正确的值,但在 http 解析并发出将由订阅函数接收的值之后。 Got it?知道了?

From the Angular Guide on Observables :来自ObservablesAngular 指南

Observables可观察对象

Observables provide support for passing messages between publishers and subscribers in your application. Observables 支持在应用程序中的发布者和订阅者之间传递消息。 Observables offer significant benefits over other techniques for event handling, asynchronous programming , and handling multiple values. Observables 在事件处理、异步编程和处理多个值方面提供了优于其他技术的显着优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM