首页 > 解决方案 > Angular 5 HttpClient 无法填充变量文本

问题描述

我的 Angylar5 组件之一有问题。我想对一个接收两个 GET id 的 api 执行一个 get 请求:登录名和密钥。密钥将得到验证,如果密钥正常,将给出一个令牌作为响应。

console.log(this.authenticationKey) 显示未定义。如果我将 console.log(res) 放在 http.get 函数中,将记录正确的响应,为什么?

编码:

import { Component, OnInit, Input } from '@angular/core';
import { DataDevicesService } from '../data-devices.service';
import { NgForm } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
declare var jquery:any;
declare var $ :any;

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  authenticationKey: string;
  authenticationToken: string;
  authenticationUrl = 'http://192.168.33.10/fortimanager/v1/api.php?login=authenticate&key=';

  constructor(private http: HttpClient) { }

  @Input() title: string;

  ngOnInit() {
  }

  executeAuthentication() {
    this.http.get(this.authenticationUrl + this.authenticationKey, {responseType: 'text'}).subscribe(res => {this.authenticationToken = res});
  }

  // changeToken():void {
  //   this.executeAuthentication()
  //     .subscribe(data => this.authenticationToken = data);
  // }

  onSubmit(f: NgForm) {
    console.log(f.value);
    this.authenticationKey = f.value["key"];
    // DO SOMETHING WITH THE AUTHENTICATION TOKEN, LOGIC COMES HERE
    console.log(this.authenticationToken);
    $('#authenticateModal').modal('hide');
    //location.reload();
  }

谁能帮帮我?谢谢!

标签: angular

解决方案


首先你需要知道什么是 Observables:

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

Observables是声明性的——也就是说,您定义了一个用于发布值的函数,但在消费者订阅它之前它不会执行。然后订阅的消费者会收到通知,直到函数完成,或者直到他们取消订阅。

你需要等待你的变量被定义。

当你在你的变量console.log()之外调用时,你subscribe的变量还没有定义

欲了解更多信息:链接


推荐阅读