【发布时间】: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