angular - Angular 5 HttpClient 无法填充变量文本
问题描述
我的 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();
}
谁能帮帮我?谢谢!
解决方案
首先你需要知道什么是 Observables:
Observables
为在应用程序中的发布者和订阅者之间传递消息提供支持。Observables 在事件处理、异步编程和处理多个值方面提供了显着优于其他技术的优势。
Observables
是声明性的——也就是说,您定义了一个用于发布值的函数,但在消费者订阅它之前它不会执行。然后订阅的消费者会收到通知,直到函数完成,或者直到他们取消订阅。
你需要等待你的变量被定义。
当你在你的变量console.log()
之外调用时,你subscribe
的变量还没有定义
欲了解更多信息:链接
推荐阅读
- dataframe - where子句值的pyspark数据帧计数等于
- sed - 使用 sed 删除特定字符和换行符
- ubuntu - Debian 10 上的 Curl 返回错误 html 而不是 pdf
- html - 表:以百分比表示的列宽与以像素为单位的最小宽度
- c++ - c++直方图随机数
- reactjs - 在表格单元格中使用tippyjs-react
- sqlite - 慢sqlite EF任何状态
- python - Regex - stop after first match with version numbers
- javascript - JavaScript 检查数组对象的值是否是其他数组对象的值
- postgresql - 在 postgreSQL 数据库中加入 tstzrange