Wuxt.js (Nuxt.js) getting out data from axios response - axios

I want to fetch out menu items from the Wordpress json response with Wuxt framework (Nuxt + Wordpress), but I can't access the data object outside the fetch (error message is that data is not defined)
This is my code
<script>
import axios from 'axios'
import Logo from '~/components/Logo'
export default {
components: {
Logo
},
async fetch ({ params, error }) {
try {
let { data } = await axios.get('http://localhost:3080/wp-json/wuxt/v1/menu')
return data
} catch (e) {
error({ message: 'Not found', statusCode: 404 })
}
}
}
</script>
How can the data object be accessed, for inserting into the template?

If you are using fetch than all your data should be commiting into store, and accessed from it. If you want to return data, use asyncData method.

I had to change the code a bit, that it returns a data function with variable, so it looks like this.
export default {
components: {
Logo
},
data() {
return { menus: [] }
},
mounted() {
fetch('http://localhost:3080/wp-json/wuxt/v1/menu')
.then(response => {
response.json().then(menus => {
this.menus = menus;
})
})
}
}

Related

Axios Vue Js: How to get the value of this object to show in api get request url

this is my vue file which accepts the id from table. this works I can get the data id from the table row
showProd (id) {
Products.showProd().then((response) => {
console.log(show1prod.product_name)
})
.catch((error) => {
alert(error)
})
this is my config file for calling the axios.get I can reach the backend but not generating the query because this url/api sends an object I believe not the id number
export default {
async showProd(id) {
return Api.get('/products/{id}',id)
},
loadProds () {
return Api.get('/products')
}
}
First make sure your API call is correct:
export default {
showProd(id) { // async not needed, axios returns promise
return axios.get('/products/' + id)
},
loadProds () {
return axios.get('/products')
}
}
You can than call these functions:
showProd (id) {
Products.showProd(id).then((response) => { // Note the id in the call
console.log(response.data.product_name) // Use the response object
})
.catch((error) => {
alert(error)
})

cannot retrieve data from angular http

I'm trying to retrieve data from a collection in my mongodb using http module using the code below,
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts').map(res => {
console.log("mapped result",res);
res.json()
});
}
It fails everytime with a response
Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.webpackJsonp.../../../http/#angular/http.es5.js.Body.json (http.es5.js:797)
at MapSubscriber.project (auth.service.ts:45)
at MapSubscriber.webpackJsonp.../../../../rxjs/operators/map.js.MapSubscriber._next (map.js:79)
at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1226)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
but when I try it with postman, I'm getting the expected result which is this,
I'm returning the response from the service and subscribing its data from a component like this,
ngOnInit() {
this.auth.getPosts().subscribe(data => {
this.value = data.posts;
console.log("blog component",this.value)
},err => {
console.log(err);
})
}
What am I doing wrong? Any help would be much appreciated
You need to convert the response in map and subscribe to it to get the final JSON response
Updated code would look like this-
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts')
.map(res => res.json())
.subscribe((data: any) => {
//console.log(data);
});
}
I hope this helps. :)
Try returning inside the .map()
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts').map(res => {
console.log("mapped result",res);
return res.json()
});
}
}
or drop the brackets (this gives you an implied return),
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts')
.map(res => res.json() );
}
}

How to invoke component to update data?

I have a main component with 2 sub-components (update, profile).
On update component, I have a form with several input fields. When I submit a form, profile section information should update after a successful request.
The problem is, profile information doesn't update after a successful request.
So, how to invoke profile component to refresh updated data? I tried to call a service after successful request, but no luck.
By the way, parent service looks like:
#Injectable()
export class AvailabilityService {
constructor(private http: Http) {
}
getProfile() {
return this.http.get(API_URL + '/user/profile')
.map(this.extractData)
.catch(this.handleError);
}
freeOwnersParking(availableDates: AvailableDates) {
let domain = API_URL + '/parking/availability';
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(availableDates);
return this.http.put(domain, body, options)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Observable.throw(errMsg);
}
}
UPDATE
Get profile:
getProfile() {
this.availabilityService.getProfile()
.subscribe(
profile =>this.profile = profile,
error => this.errorMessage = <any>error
);
}
Update profile:
freeOwnersParking() {
this.availabilityService.freeOwnersParking(this.availableDates)
.subscribe(
response => this.availabilityService.getProfile(),
error => this.errorMessage = error
);
}
You need to leverage a shared service between them to notify the profile component.
For example an UpdateProfileService with an observable / subject in it. In this case, the profile component can subscribe on it to be notified.
Here is the service:
#Injectable()
export class UpdateProfileService {
profileUpdated:Subject<boolean> = new Subject();
(...)
updateProfile(profile:any) {
return this.http.put('http://...', profile)
.map(res => {
this.profileUpdated.next(true);
return res.json();
});
}
}
and within the profile component:
#Component({
(...)
})
export class ProfileComponent {
constructor(private service:UpdateProfileService) {
this.service.profileUpdated.subscribe(() => {
// Update bound data for profile
});
}
}

How to use the login credentials with php in ionic project

I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});

Debugging Ember-cli-mirage when routes are not being called

I have successfully created one route in ember-cli-mirage, but am having trouble loading the related data.
The API should be returning JSON API compliant data.
I'm not really sure if there are any good methods or not for debugging mirage's request interception. Here is my config.js
export default function() {
this.urlPrefix = 'https://myserver/';
this.namespace = 'api/v1';
this.get('/machines', function(db, request) {
return {
data: db.machines.map(attrs => (
{
type: 'machines',
id: attrs.id,
attributes: attrs
}
))
};
});
this.get('/machines/:id', function(db, request){
let id = request.params.id;
debugger;
return {
data: {
type: 'machines',
id: id,
attributes: db.machines.find(id),
relationships:{
"service-orders": db["service-orders"].where({machineId: id})
}
}
};
});
this.get('/machines/:machine_id/service-orders', function(db, request){
debugger; // this never gets caught
});
}
Most of this is working fine (I think). I can create machines and service orders in the factory and see the db object being updated. However, where my application would normally make a call to the api for service-orders: //myserver/machines/:machine_id/service-orders, the request is not caught and nothing goes out to the API
EDIT:
This is the route that my Ember app is using for /machines/:machine_id/service-orders:
export default Ember.Route.extend(MachineFunctionalRouteMixin, {
model: function() {
var machine = this.modelFor('machines.show');
var serviceOrders = machine.get('serviceOrders');
return serviceOrders;
},
setupController: function(controller, model) {
this._super(controller, model);
}
});
And the model for machines/show:
export default Ember.Route.extend({
model: function(params) {
var machine = this.store.find('machine', params.machine_id);
return machine;
},
setupController: function(controller, model) {
this._super(controller, model);
var machinesController = this.controllerFor('machines');
machinesController.set('attrs.currentMachine', model);
}
});
Intuitively, I would think that machine.get('serviceOrders'); would make a call to the API that would be intercepted and handled by Mirage. Which does not seem to be the case