I am trying to authenticate to a service using http.post. It took me some time to figure out how to bypass the cross origin problem, basically disabling the check in Safari (developing on Mac). The following code works, but I need to press the login button twice to get the login to succeed.
When the loginUser function is called the first time, the console shows “undefined” the second time, it get the expected value. What am I doing wrong?
auth-service.ts
login() {
var headers = new Headers();
headers.append('Access-Control-Allow-Origin','*');
return this.http.post(this.url, "null", {headers: headers})
.map(response => response.json());
}
page1.ts
loginUser() {
this.auth.login()
.subscribe(
data => { this.data = data},
err => { this.error = true }
);
console.log(this.data);
}
I have tried the following approach as well but same problems.
page1.ts
loginUser() {
console.log("Initiating Login Operation");
this.auth.login2()
.then(
data => { this.data = data},
err => { this.error = true }
);
console.log(this.data);
}
auth-service.ts
login2() {
var headers = new Headers();
headers.append('Access-Control-Allow-Origin','*');
if (this.data) {
// already loaded data
console.log("Already have data!");
// This is where I land the second time the function is called.
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise((resolve, reject) => {
this.http.post(this.url, "null", {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log("In Subscribe Method");
this.data = data;
resolve(this.data);
}, (err) => {reject(err)});
});
}