xhttp.onreadystatechange return 未定义 xhttp.responseText

xhttp.onreadystatechange return undefined xhttp.responseText

我试图通过从另一个 组件 调用它来访问 xhttp.responseText 但它显示未定义。比我试图从外部访问它 xtthp.onreadystatechange. 它再次显示未定义。请帮助我。我想从另一个组件访问它(login.component.ts).

这是文件。

filedata.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
    }
}

filedata.component.html

<div>
    <button type = "button" (click) = "makeRequest()">File Test</button>
    <p id = "demo"></p>
</div>

login.component.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"]);
}

更新:我认为您需要 return 异步功能。像这样尝试:

makeRequest(): any {
  return new Promise(resolve => {
  let xhr = new XMLHttpRequest();
  xhr.withCredentials = true;
  xhr.open("GET", 'http://localhost/Angular-cli/login/employees.txt', true);
  xhr.onreadystatechange = () => {if(xhr.readyState === 4 && xhr.status === 200)  resolve(xhr.responseText);};
  xhr.send();
});
}

然后使用这个函数:

this.filedata.makeRequest().then(res => { if(res) {/* do what u want */}  })

更新 2:更好地使用这样的请求:

import { Http, RequestOptions, Response, Headers} from '@angular/http';
import { Observable } from "rxjs";

constructor(private http: Http){}

functionName() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ withCredentials: true, headers });
return this.http.get(`your url here`, options)
  .map((res: Response) => {
    return res.json();
  })
  .catch((error: Response) => {
    return Observable.throw(`error: ${error}`);
  })

}

然后在组件中调用函数