ionic2 Property does not exist on type '{}' - json

I am getting a json in typescript in ionic framework.
The json is:
{
"result": "success",
"user": {
"loggedIn": true,
"name": "Nulra",
"password": ""
}
}
And I print the data:
console.log("NULRA CHECKING: " + data.result + " " + data.user);
It gives the error:
Typescript Error
Property 'result' does not exist on type '{}'.
Property 'user' does not exist on type '{}'.
auth-service.ts:
login(credentials) {
let opt: RequestOptions;
let myHeaders: Headers = new Headers;
myHeaders.set('Accept', 'application/json; charset=utf-8');
myHeaders.append('Content-type', 'application/json; charset=utf-8');
opt = new RequestOptions({
headers: myHeaders
})
return new Promise((resolve, reject) => {
this.http.get(apiUrl+'login/0/login?email='+credentials.email+'&password='+credentials.password, opt)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
},(err) => {
reject(err);
});
});
}
In login.ts:
doLogin(){
this.authService.login(this.loginData)
.then(data => {
console.log("NULRA CHECKING: " + data.result + " " + data.user);
}
.catch(err => {
});
}
Anyone know how to deal with it? because the json I confirmed have result and user. Thanks a lot.
when console.log(data):

Try this-
public userData: any = {};
doLogin(){
this.authService.login(this.loginData)
.then(data => {
this.userData = data;
console.log(`NULRA CHECKING: ${this.userData.result} ${this.userData.user}`);
}
.catch(err => {
});
}

Well, I got this solved when I simple called data['result'] instead of data.result;
For me it appeared only when i first executed ionic serve.

Related

TypeError: JSON.stringify(...).then is not a function - React JS

I am trying to connect my react app with the backend for log in page. I am using a promise to return a success message.
login.js
onSubmitSignIn = () => {
fetch('http://localhost:5000/', {
method : 'post',
headers :{ 'Content-Type' : 'application/json'},
body : JSON.stringify({
userId : this.state.userId,
password : this.state.password
}).then(response => response.json())
.then(data => {
if(data === 'success'){
this.props.onRouteChange('home');
}
})
})
}
Backend code -
exports.findById = (req) => {
return new Promise((resolve) => {
var sql = "Select * from users where userid = '" + req.body.userId + "' ;";
connection.query(sql,req, function (error, results, fields) {
var data = JSON.parse(JSON.stringify(results));
var valid = false;
if( data.length !=0 && req.body.userId === data[0].userid && req.body.password === data[0].password)
valid = true;
if(valid) {
resolve({message : "success"});
}else{
reject({ message :"fail"});
}
});
})
};
After clicking on sign in button, I am getting an error "TypeError: JSON.stringify(...).then is not a function"
I tried some solutions from similar questions, it did not work in my case.
The then should be outside of fetch
fetch('http://localhost:5000/', {
method : 'post',
headers :{ 'Content-Type' : 'application/json'},
body : JSON.stringify({
userId : this.state.userId,
password : this.state.password
})
}).then(response => response.json())
.then(data => {
if(data === 'success'){
this.props.onRouteChange('home');
}
})
You have a typo, .then should be on fetch not on JSON.stringify.
onSubmitSignIn = () => {
fetch("http://localhost:5000/", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: this.state.userId,
password: this.state.password
})
})
//-^
.then(response => response.json())
.then(data => {
if (data === "success") {
this.props.onRouteChange("home");
}
});
};
you have missed a bracket. there should be a closing bracket after JSON.stringify().
onSubmitSignIn = () => {
fetch('http://localhost:5000/', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: this.state.userId,
password: this.state.password
})
}).then(response => response.json())
.then((data) => {
if (data === 'success') {
this.props.onRouteChange('home');
}
});
};
I had this problem too. Check and confirm that you're not importing or requiring {JSON} in your application. It's most likely referring to that imported JSON rather than the global

parse xml to json and subscribe with Angular4

I'm trying to convert an XML string to JSON by using xml2js, then i need to send and subscribe the result in another component.
getLastWeekSnow = function(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password'));
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
xml2js.parseString( res.text(), function (err, result) {
console.dir(result); //Prints JSON object!
});
})
.subscribe(data => {
console.log(data); //Undefined !
});
}
so the console.dir(reults) gives me back what i need but in the subscribe (console.log(data)) i get undefined.
Why am i getting undefined in the subscribe , but gets the right Object in the .map ?
Make sure to return your data, otherwise it cannot subscribe
getLastWeekSnow = function(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password'));
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
let data;
xml2js.parseString( res.text(), function (err, result) {
console.dir(result); //Prints JSON object!
data = result
});
return data;
})
.subscribe(data => {
console.log(data); //Undefined !
});
}

AspNetCore EntityModel can't serialize to Json

I'm working on a project in AspNetCore with EntityFrameworkCore and i would like to use Ajax to get an object but my controller can't serialize this object correctly in Json, so my Ajax call trigger an error instead of a success event.
Here is my controller + test JsonConvert that return null.
[HttpGet]
public async Task<IActionResult> GetPackWithAllCards(int? packId)
{
if (packId == null)
{
return Json("An error has occured");
}
else
{
var pack = await _context.Packs
.Include(p => p.TagPacks)
.ThenInclude(tp => tp.Tag)
.Include(p => p.CardPacks)
.ThenInclude(cp => cp.Card)
.ThenInclude(c => c.FaceCards)
.ThenInclude(fc => fc.Face)
.ThenInclude(fc => fc.Template)
.Include(p => p.CardPacks)
.ThenInclude(cp => cp.Card.FaceCards)
.ThenInclude(fc => fc.Face.Image)
.Include(p => p.CardPacks)
.ThenInclude(cp => cp.Card.FaceCards)
.ThenInclude(fc => fc.Face.Sound)
.SingleOrDefaultAsync(m => m.PackId == packId);
//pack is correctly returned from database
if (pack == null)
{
return Json("An error has occured");
}
var a = JsonConvert.SerializeObject(pack);
return Ok(pack);
}
}
and my ajax call with typescript object:
var pack = new Pack(0, 0, 0, "", "", 0, 0, false, null, null);
$.ajax({
type: "GET",
url: "/pack/GetPackWithAllCards",
dataType: "text",
data: {packId},
async: false,
success: function (response) {
$.extend(pack, response);
alert("succes:"+response.packId);
},
error: function (response) {
$.extend(pack, response);
alert("error:" + response);
}
});
alert(pack);
return pack;
I hope someone could help me, i really don't find a solution to my problem.
I do this:
return new ContentResult
{
Content = JsonConvert.SerializeObject(data, Formatting.None, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}),
ContentType = "application/json"
};
Are you getting the packId value in the controller? you may need to use:
data: {packId : packId},

Convert Promise object to JSON in Angular 2

I'm trying to make an HTTP POST and then check the response to see if it fails or succeeds.
The HTTP call looks like this :
doLogin(credentials) {
var header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
var body = 'username=' + credentials.username + '&password=' + credentials.password;
return new Promise((resolve, reject) => {
this.http.post(this.url, body, {
headers: header
})
.subscribe(
data => {
resolve(data.json());
},
error => {
resolve(error.json());
}
);
});
}
And the call of this function is the following :
data: Object;
errorMessage: Object;
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).then(
result => {
this.data = result;
console.log(this.data);
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
On Chrome console, the data is the following :
Object {status: "Login success", token: "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjcmlzdGkiLCJ1c2VyS…blf1AzZ6KzRWQFNGXCrIeUHRG3Wrk7ZfCou135WmbVa15iYTA"}
How can I access the status in Angular 2? Because if I'm trying to access this.data.status, it's not working.
Should I create a class with the status and token properties?
To answer your question, you can use the response.okboolean that's available in the subscription of the observable from the http.
So based on your code you could pass the data object straight to the promise and inspect data.ok before parsing the data.json.
//...
return new Promise((resolve, reject) => {
this.http.post(this.url, body, {
headers: header
})
.subscribe(resolve,
error => {
reject(error.json());
}
);
});
// then you would have something like this:
this._loginService.doLogin(this.credentials).then(
result => {
if (result.ok) {
this.data = result;
console.log(this.data);
}
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
})
SUGGESTION
Now, I would recommend getting rid of the promise, as I believe you don't really need it. whoever is consuming your service can just subscribe to the observable returned by the http post, like so:
doLogin(credentials) {
let header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
var body = 'username='+credentials.username+'&password='+credentials.password;
return this.http.post(this.url, body, { headers: header });
}
Then, when logging in:
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).subscribe(response => {
if (response.ok) { // <== CHECK Response status
this.data = response.json();
console.log(this.data);
} else {
// handle bad request
}
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
Hope this helps!
You could do it like this:
data: Object;
errorMessage: Object;
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).then(
(result: any) => {
this.data = result;
console.log(this.data);
console.log(this.data.status);
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
Set the result to type any. That way you'll be able to access the status, however you could create a class and use rxjs/map within your service to populate the class if you so desire.

React + Fetch+ Json. TypeError: Cannot read property of undefined

When I used SuperAgent I didn't have this problem, but I decided to use Window.fetch polifyl and I met this problem. I see all data was loaded, but it still shows error.
Could your help me identify this error please:
In render() I genereate a list of components based on an obtained list:
render() {
if (this.state.data.list) {
console.log("render: " + this.state.data.list);
var counter = 0;
const list = this.state.data.list.map((item) => {
....
The promise handlers in your screenshot won't work:
.then((json) => console.log('parsed json: ', json))
.then((json) => { this.setState({ data: json }); })
"Take the value from resolving this promise and pass it to console.log. Then, take console.log's return value (which is undefined) and pass it to this.setState."
fetch(url, {
headers: {
'Accept': 'application/json',
},
}).then((response) => response.json()
.catch(err => {
console.err(`'${err}' happened!`);
return {};
}))
.then((json) => {
console.log('parsed json: ', json);
this.setState({ data: json })
})
.catch((err) => { console.log('fetch request failed: ', err) }
)