【问题标题】:Angular 5 HttpClient cannot fill variable textAngular 5 HttpClient 无法填充变量文本
【发布时间】:2018-06-15 17:17:09
【问题描述】:

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

  • PS,我知道这不是最安全的身份验证方式 *

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

谁能帮帮我?谢谢!

【问题讨论】:

  • 请记住 http.get 返回一个 observable,这是一个异步调用。因此,任何不等待 http 调用完成的逻辑都可能过早产生结果。将您的 console.log 放入您的订阅中进行测试。

标签: angular


【解决方案1】:

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

Observables 支持在应用程序中的发布者和订阅者之间传递消息。在事件处理、异步编程和处理多个值方面,Observable 与其他技术相比具有显着优势。

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

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

当您在 subscribe 之外调用 console.log() 时,您的变量尚未定义

欲了解更多信息:link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-17
    • 2018-09-05
    • 1970-01-01
    • 2016-10-13
    • 2018-11-07
    • 2016-07-22
    • 2018-07-16
    • 1970-01-01
    相关资源
    最近更新 更多