我试图通过从另一个组件调用xhttp.responseText来访问它,但它显示未定义。比我尝试从xtthp.onreadystatechange 外部访问它。它再次显示未定义。请帮助我。我想从另一个 Component( login.component.ts )访问它。
这是文件。
文件数据.component.ts
import { Component, OnInit } from '@angular/core';
@Component(
{
selector: "file",
templateUrl: "./filedata.component.html",
})
export class FileData
{
makeRequest(): string
{
let input;
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState === 4 && this.status === 200)
{
// here it's good
document.getElementById("demo").innerHTML = this.responseText;
input = this.responseText;
}
};
document.getElementById("demo").innerHTML = input; //here it's undefined
xhttp.open("GET", 'http://localhost/Angular-cli/login/employees.txt', true);
xhttp.send();
return input; //I want to call it from login.component.ts
}
}
文件数据.component.html
<div>
<button type = "button" (click) = "makeRequest()">File Test</button>
<p id = "demo"></p>
</div>
登录组件.ts
import { Component, OnInit } from '@angular/core';
import { AdminAccount } from '../admin/admin.component';
import { Router } from "@angular/router";
import {ReactiveFormsModule, FormsModule} from "@angular/forms";
import { FileData } from "../filedata/filedata.component";
@Component(
{
selector: "login",
templateUrl: "./login.component.html"
})
export class LoginForm
{
data = {username: "", password: ""};
input = {username: "", password: ""};
constructor(private router: Router, private filedata: FileData){}
formSubmit()
{
console.log("Input file data for login:", typeof(this.filedata.makeRequest()));
if(this.filedata.makeRequest()) //here it is undefined.
{
this.input.username = this.filedata.makeRequest().split("??")[0];
this.input.password = this.filedata.makeRequest().split("??")[1];
if(this.data.username == this.input.username && this.data.password == this.input.password)
{
this.router.navigate(["/admin"]);
}
else
console.log("Wrong User or Pass");
}
else
console.log("Undefined!");
this.data.username = "";
this.data.password = "";
}
}
我想通过调用makeRequest来访问responseText。有什么建议吗?我应该怎么做才能在此处访问responseText。
this.input.username = this.filedata.makeRequest().split("??")[0];
this.input.password = this.filedata.makeRequest().split("??")[1];
if(this.data.username == this.input.username && this.data.password ==
this.input.password)
{
this.router.navigate(["/admin"]);
}