0

I'm trying to access xhttp.responseText by calling it from another component but it shows undefined. Than I tried to access it from outside xtthp.onreadystatechange. Again it shows undefined. Kindly help me. I want to access it from another Component(login.component.ts).

Here's the files.

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 = "";
    }
}

I want to access responseText here by calling makeRequest. Any suggestions what's going on? What should I do to access responseText here.

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"]);
}
Zeeshan Malik
  • 627
  • 1
  • 14
  • 31

1 Answers1

0

UPDATED: I think you need return async function. Try like this:

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

then use this function:

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

UPDATED 2: better use requests like this:

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

}

then call function in component

FierceDev
  • 685
  • 6
  • 13
  • FierceDev: Well thanks very much. But now I get new error
    Access-Control-Allow-Origin' header in the response
    So I install chrome extention. But I don't know how to set URL pattern of extention.
    – Zeeshan Malik Jul 24 '17 at 16:50
  • Try to remove "xhr.withCredentials = true". – FierceDev Jul 24 '17 at 16:55
  • If remove not help you, try "xhr.setRequestHeader('Access-Cross-Allow-Origin','*')" – FierceDev Jul 24 '17 at 16:58
  • This gives, this. :/ **XMLHttpRequest cannot load http://localhost/Angular-cli/login/employees.txt. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.** – Zeeshan Malik Jul 24 '17 at 17:13
  • You try my last comment? – FierceDev Jul 24 '17 at 17:15
  • nothing happened with "xhr.withCredentials = true". Above error is generated by setting header. – Zeeshan Malik Jul 24 '17 at 17:24
  • before line "xhr.open("GET", 'http://localhost/Angular-cli/login/employees.txt', true);" add xhr.setRequestHeader('Access-Cross-Allow-Origin','http://localhost:4200'); – FierceDev Jul 24 '17 at 17:28
  • This gives, this and if I add **header** after **open** error stay still. **core.es5.js:1020 ERROR Error: Uncaught (in promise): InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. Error: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.** – Zeeshan Malik Jul 24 '17 at 17:32
  • I think it help you: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS. If my answer help you, please mark it :) – FierceDev Jul 24 '17 at 17:50
  • Find green check image – FierceDev Jul 24 '17 at 18:03
  • when I click up arrow, blue popup appears and vote toggle from 0 to 1 to 0. – Zeeshan Malik Jul 24 '17 at 18:14
  • See image, not up arrow – FierceDev Jul 24 '17 at 18:16
  • Good luck in your projects :) – FierceDev Jul 24 '17 at 18:25
  • I updated answer again, maybe it help you, but i solved CORS problem with flag "--disable-host-check" in my "ng serve" script – FierceDev Jul 24 '17 at 19:15
  • I updated **filedata.component.ts.** And to catch observable I add this.filedata.makeRequest().subscribe(input => { console.log(input); this.input.username = input[1].split("??")[0]; this.input.password = input[1].split("??")[1]; if(this.data.username == this.input.username && this.data.password == this.input.password) { this.router.navigate(["/admin"]); } }); in **login.component.ts.** – Zeeshan Malik Jul 25 '17 at 16:32
  • but it didn't work. and now status and readystate are also **0**. – Zeeshan Malik Jul 26 '17 at 05:29