fetch api and json - json

For some reason the second then command in my js file line 12 seems to be nonconductant.
Why is that ? Thanks
Edit: The questionn should have been : For some reason the second console.log does not give an output.
This question has been sucessfully answered by the commentators. Thank you
codepen
document.getElementById('btn').addEventListener('click', btnPressed);
function btnPressed() {
fetch("https://randomuser.me/api")
.then(function(res) {
console.log(res);
return res.json();
})
.then(function(data) {
console.log(data);
})
.catch(err => console.log('Error,with message:', err.statusText))
}
<button id=btn>Button</button>

Both console.log functions are working... Please run the below code.
document.getElementById('btn').addEventListener('click', btnPressed);
function btnPressed() {
fetch("https://randomuser.me/api")
.then(function(res) {
console.log("...................1st console Start");
console.log(res);
console.log("...................1st console End");
return res.json();
})
.then(function(data) {
console.log("...................2nd console Start");
console.log(data);
console.log("...................2nd console End");
})
.catch(err => console.log('Error,with message:', err.statusText))
}
<button id=btn>Button</button>

Related

Call json file from url

I'm trying to call json file from url and get data. But no error and nothing working. I don't have any idea how to solve it.
service
export class JsonService {
public getMenuData(): Observable<any> {
return new Observable((observer) => {
this.http.get('https://demored.ddns.net:50443/demored/path_image/menu.json').subscribe((response)=> {
observer.next(response);
observer.complete();
});
});
}
Component
ngOnInit() {
this.getJson();
}
getJson(){
this.jsonService.getMenuData().toPromise().then(data => {
this.menuJson = data;
console.log("Menu from json file ",this.menuJson);
}).catch((err) => {
console.log('error in fetching data',err);
});
}
You make the GET request on the service, where you convert the request into a promise with toPromise(). From there in any component you can call the method for the service declared in the constructor this.serviceJson() and resolve the promise with a .then () or .catch ()
export class JsonService {
getMenuData(): Promise<any> {
return this.http.get<any>('https://demored.ddns.net:50443/demored/path_image/menu.json').toPromise()
}
component
ngOnInit() {
this.getJson();
}
async getJson(){
await this.jsonService.getMenuData().then(data => {
this.menuJson = data;
console.log("Menu from json file ",this.menuJson);
}).catch((err) => {
console.log('error in fetching data',err);
});
}

this is undefined at axios promise - vuejs

Im registering my axios globally and then using it at every component using this.$axios
I have a save method and items which is an array at my component data.
At my save method i have this piece of code:
this.$axios
.put(`HardwareBoardTracking`, this.items[this.editedIndex])
.then((res) => {
console.log(res);
this.items[this.editedIndex].actions.forEach((test) => {
this.items.forEach((card) => {
if (card.id != this.items[this.editedIndex].id) {
this.addnewActionToCard(card, test);
}
});
});
})
.catch((err) => {
console.log("error caught");
console.log(err);
Object.assign(this.items[this.editedIndex], elementForFail);
});
When getting to then block with debugger i can see this is undefined
This is the error i get:
Uncaught (in promise) TypeError: Cannot convert undefined or null to object
at Function.assign (<anonymous>)
for testing purposes i tried to add testMethod and call it from the promise like this:
testMethod() {
console.log("Test Method");
console.log(this);
},
save() {
const elementForFail = { ...this.editedItem };
if (this.editedIndex > -1) {
Object.assign(this.items[this.editedIndex], this.editedItem);
this.items[this.editedIndex].CompletedAllActions = true;
this.items[this.editedIndex].actions.forEach((element) => {
this.addnewActionToCard(this.items[this.editedIndex], element);
});
this.$axios
.put(`HardwareBoardTracking`, this.items[this.editedIndex])
.then((res) => {
console.log(res);
this.testMethod();
this.items[this.editedIndex].actions.forEach((test) => {
this.items.forEach((card) => {
if (card.id != this.items[this.editedIndex].id) {
this.addnewActionToCard(card, test);
}
});
});
})
.catch((err) => {
console.log("error caught");
console.log(err);
Object.assign(this.items[this.editedIndex], elementForFail);
});
And the method is called and inside it it this is defined properly and logged to consol like this:
VueComponent {...}
I Found this answer https://stackoverflow.com/a/45217521 which looks like exactly what i need, But none of the solution works.
If i try the .bind(this) solution, this is still undefined but it does continue with execution and then i get this error:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler: "TypeError: this.$axios.put(...).then(...).bind is not a function"
html tag added for colorized code

How do I wait for fetch to finish and load content before continuing with program execution

This is my function which gets data from a specific url and stores it in local storage, later on I will call it for a specific URL and display and work with content from local storage.
This fetch takes aproximately 1.5 seconds to resolve so things aren't displayed after first click on a button that calls this function. How do I wait for fetch to finish and load content before continuing with program execution?
function getContent(url) {
fetch(url)
.then(response => response.json())
.then(function store(data) {
localStorage.clear();
localStorage.setItem("data", JSON.stringify(data.hits));
})
.catch(function (error) {
console.log('Request failed', error);
});
}
This is what I tried
async function getContent(url) {
await fetch(url)
.then(response => response.json())
.then(function store(data) {
localStorage.clear();
localStorage.setItem("data", JSON.stringify(data.hits));
})
.catch(function (error) {
console.log('Request failed', error);
});
}
You should try this code:
async function getContent(url) {
try {
const response = await fetch(url);
const data = await response.json();
localStorage.clear();
localStorage.setItem('data', JSON.stringify(data.hits));
} catch (error) {
console.log('Request failed', error);
}
}

Catch/Display errors in client side without console logs

When a promise is called in the client side. What is the best way to catch/display error without console.log()? Example as follows
.then(result => {
})
.catch(err => {
console.log(err);
});
Maybe you are looking for:
console.error = () => { throw new Error(FEATURES_ERROR); };
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

Angular 2 this.data is undefined

I'm trying to read the content of my JSON file through my "GetJsonService".
app.component.ts:
data: any;
constructor(private jsonService: GetJsonService) {}
ngOnInit() {
this.getRecords();
console.log(this.data);
}
getRecords() {
this.jsonService.getRecords().subscribe(data => {
this.data = data;
}, err => {
console.log(err);
});
}
get-json.service.ts
constructor(private http: Http) { }
data: any;
getRecords() {
return this.http.get('assets/standorte.json').map(data => {
this.data = data.json();
return data.json();
}, err => {
if (err) {
return err.json();
}
});
}
I want to put the content of data.json() into this.data to use it.
But when I log this.data it is "undefined".
I'm completely new to Angular 2 and Typescript, so I really would be thankful when someone helps me.
Greetings
#MauricioSipmann solved my problem.
The problem was that the code runs asynchronously in a request.
I actually knew that but Typescript confused me a little bit.
Thank you to all responders!
Just modify your method getRecords()
Use it as below :
getRecords() {
this.jsonService.getRecords().subscribe(data => {
this.data = data;
console.log(this.data);
}, err => {
console.log(err);
});
}
Instead of logging after calling method you should do inside success of service.
This is common issue which every developer face at initiate stage of Angular 2+.
It is an async call. So the issue is you console.log() statement is executing before your service assign value this.data = data; to the variable.
With your code if you display data in HTML it will probably work fine. Just it will not log properly where you got confused.
If you are using angular 6, no need to convert to json. Just return the request.
getRecords() {
return this.http.get('assets/standorte.json')
}
another problem is your not re throw the async state ..try this:
ngOnInit() {
this.getRecords().then((resp)=>{
console.log(resp);
});
}
getRecords() {
return new Promise<>((resolve,reject)
=> {
this.jsonService.getRecords().subscribe(data => {
this.data = data;
resolve(data);
}, err => {
console.log(err);
reject(err);
});
})
}