ReferenceError: data is not defined in angular 6 - api

Im calling a service from one of my component, via the assignGirdle function. While this service is being executed, I get the above error, but when I check in the network tab and click on the API call, in response in can see the data.
Note girdleNew is of type any. Also this function I'm calling on ngOnInit()
assignGirdle() {
this.diamondSearchService.getDistinctValues()
.subscribe((data) => {
this.girdleNew = data;
}, error => {
this.alertify.error(error);
});
}
The service:
getDistinctValues() {
return this.authHttp
.get(this.baseUrl + 'distinct/girdle')
.map(response => response.json())
.catch(this.handleError);
}

Check if you have imported service in your component. Below is my data service import.
import { DataService } from '../data.service';
Create object of the same in your component:
constructor(public data: DataService) { }
In my component I have called this getUser() method which is defined in DataService.
this.data.getUser(email).subscribe( data => {
if(data.length > 0){
console.log(data);
}
});
Below is my service:
getUser(email){
// definition
}
This works for me.

Related

Accessing Vue.$router inside an external "service" class

I have a service which extends EventEmitter.
services/service/service.js (relative to main.js)
import { EventEmitter } from "events";
class Service extends EventEmitter {}
Inside the Service class, I have the following method which returns a Promise:
/**
* Method to fetch the Active Survey by "surveySlug":
*/
fetchActiveSurvey(serviceSlug) {
return new Promise((resolve, reject) => {
axios.get(`${this.baseURL}/service/${serviceSlug}`, { headers: { Authorization: AuthStr } }).then(response => {
resolve(response.data);
}).catch(error => {
if (error.response && error.response.data.status != 200) {
Vue.$router.push({ name: 'home'});
}
});
});
}
I also have the usual routes.js in the same directory as main.js, which is working fine.
Services are then established as plugins:
import Service from "../services/service/service"; // <= Refrences `service.js`
export default {
install(Vue) {
Vue.prototype.$service = Service;
}
};
I have tried the following:
Vue.$router.push({ name: 'home'});
Vue.prototype.$router.push({ name: 'home'});
However, I seem to find that $router is not defined. What would be the best way to define the router push routes from inside this service?
You need to use the this keyword to access the router instance. Try:
this.$router.push({ name: 'home'});

Vue Router beforeRouteEnter API call response not 'working'

I cannot see why the function is not returning its call back correctly.
I have a list of vehicle on one route and then another route to display that vehicles resource.
This is what I have in my Single file component for the single vehicle resource:
export default {
data() {
return {
vehicle: null,
error: null
}
},
created() {
},
beforeRouteEnter(to, from, next) {
function getVehicle(id) {
console.log('called');
return axios.get(`/api/v1/vehicles/${id}`);
}
getVehicle(to.params.id, (err, vehicle) => {
console.log('response');
next(vm => vm.setData(err, vehicle))
});
},
methods: {
setData (err, vehicle) {
if (err) {
this.error = err.toString();
} else {
this.vehicle = vehicle;
}
}
}
}
This issue is that when clicking a vehicle link, the API call is correctly made and returning a valid response but yet the next() method isn't called and the console log for 'response' isn't shown neither but the 'called' one is.
Not sure on the logic behind it, but had to use .then() for my getVehicle response before it would work. So changed to:
getVehicle(to.params.id).then( response => {
next( vm =>
vm.setData(response)
);
});
I'm not sure it will work with a function inside the beforeRouteEnter guard. Instead try call the axios get method like
let data = axios.get('/api/v1/vehicles/${to.params.id})
next(vm.setData(err, data))
This should work

Execute custom functions one after another - Callback logic in Vue.js

There is a form which submits some data to an API in my component. Assume that it's method is ProcessLogin(). Inside this function I have written my API calls using axios. With the help of then() I have handled my server response and displayed my toast. All good.
Now as a part of my code clean up, I have decided to move all my axios functions to another api.js file and export functions from there. Here is an example function I have in my api.js file :
function ApiLogin(data) {
const url = `${BASE_URL}/authenticate`;
axios.post(url,data).then(response => {
return response;
}).catch(error => {
return error.response;
});
}
On the other side in my component I have my method defined as below :
methods: {
ProcessLogin() {
var status = ApiLogin(this.data);
console.log(status);
}
}
When executing this, I get undefined on my console. I know why it is happening. Because console.log(status) executes before ApiLogin could process and sends it's response. How to handle this kind of situation.? I know that callback is the rescue here, but I am not really sure about how to integrate it.
If you return the axios call from your ApiLogin function:
function ApiLogin(data) {
const url = `${BASE_URL}/authenticate`
return axios.post(url, data)
}
You could then handle the response in your component using then and console log from there:
methods: {
ProcessLogin() {
ApiLogin(this.data)
.then(res => console.log(res))
.catch(err => console.log(err))
}
}
...or with async/await:
methods: {
ProcessLogin: async function() {
try {
var status = await ApiLogin(this.data)
console.log(status)
}
catch(err) {
console.log(err)
}
}
}

Unit testing HTTP request with Vue, Axios, and Mocha

I'm really struggling trying to test a request in VueJS using Mocha/Chai-Sinon, with Axios as the request library and having tried a mixture of Moxios and axios-mock-adaptor. The below examples are with the latter.
What I'm trying to do is make a request when the component is created, which is simple enough.
But the tests either complain about the results variable being undefined or an async timout.
Am I doing it right by assigning the variable of the getData() function? Or should Ireturn` the values? Any help would be appreciated.
Component
// Third-party imports
import axios from 'axios'
// Component imports
import VideoCard from './components/VideoCard'
export default {
name: 'app',
components: {
VideoCard
},
data () {
return {
API: '/static/data.json',
results: null
}
},
created () {
this.getData()
},
methods: {
getData: function () {
// I've even tried return instead of assigning to a variable
this.results = axios.get(this.API)
.then(function (response) {
console.log('then()')
return response.data.data
})
.catch(function (error) {
console.log(error)
return error
})
}
}
}
Test
import Vue from 'vue'
import App from 'src/App'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
let mock = new MockAdapter(axios)
describe('try and load some data from somewhere', () => {
it('should update the results variable with results', (done) => {
console.log('test top')
mock.onGet('/static/data.json').reply(200, {
data: {
data: [
{ id: 1, name: 'Mexican keyboard cat' },
{ id: 2, name: 'Will it blend?' }
]
}
})
const VM = new Vue(App).$mount
setTimeout(() => {
expect(VM.results).to.be.null
done()
}, 1000)
})
})
I am not sure about moxios mock adaptor, but I had a similar struggle. I ended up using axios, and moxios, with the vue-webpack template. My goal was to fake retreiving some blog posts, and assert they were assigned to a this.posts variable.
Your getData() method should return the axios promise like you said you tried - that way, we have some way to tell the test method the promise finished. Otherwise it will just keep going.
Then inside the success callback of getData(), you can assign your data. So it will look like
return axios.get('url').then((response) {
this.results = response
})
Now in your test something like
it('returns the api call', (done) => {
const vm = Vue.extend(VideoCard)
const videoCard = new vm()
videoCard.getData().then(() => {
// expect, assert, whatever
}).then(done, done)
)}
note the use of done(). That is just a guide, you will have to modify it depending on what you are doing exactly. Let me know if you need some more details. I recommend using moxios to mock axios calls.
Here is a good article about testing api calls that helped me.
https://wietse.loves.engineering/testing-promises-with-mocha-90df8b7d2e35#.yzcfju3qv
So massive kudos to xenetics post above, who helped in pointing me in the right direction.
In short, I was trying to access the data incorrectly, when I should have been using the $data property
I also dropped axios-mock-adaptor and went back to using moxios.
I did indeed have to return the promise in my component, like so;
getData: function () {
let self = this
return axios.get(this.API)
.then(function (response) {
self.results = response.data.data
})
.catch(function (error) {
self.results = error
})
}
(Using let self = this got around the axios scope "problem")
Then to test this, all I had to do was stub the request (after doing the moxios.install() and moxios.uninstall for the beforeEach() and afterEach() respectively.
it('should make the request and update the results variable', (done) => {
moxios.stubRequest('./static/data.json', {
status: 200,
responseText: {
data: [
{ id: 1, name: 'Mexican keyboard cat' },
{ id: 2, name: 'Will it blend?' }
]
}
})
const VM = new Vue(App)
expect(VM.$data.results).to.be.null
VM.getData().then(() => {
expect(VM.$data.results).to.be.an('array')
expect(VM.$data.results).to.have.length(2)
}).then(done, done)
})

Promise isn't working in react component when testing component using jest

Good day. I have the following problem:
I have an item editor.
How it works: I push 'Add' button, fill some information, click 'Save' button.
_onSaveClicked function in my react component handles click event and call function from service, which sends params from edit form to server and return promise.
_onSaveClicked implements
.then(response => {
console.log('I\'m in then() block.');
console.log('response', response.data);
})
function and waits for promise result. It works in real situation.
I created fake service and placed it instead of real service.
Service's function contains:
return Promise.resolve({data: 'test response'});
As you can see fake service return resolved promise and .then() block should work immediatly. But .then() block never works.
Jest test:
jest.autoMockOff();
const React = require('react');
const ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
const expect = require('expect');
const TestService = require('./service/TestService ').default;
let testService = new TestService ();
describe('TestComponent', () => {
it('correct test component', () => {
//... some initial code here
let saveButton = TestUtils.findRenderedDOMComponentWithClass(editForm, 'btn-primary');
TestUtils.Simulate.click(saveButton);
// here I should see response in my console, but I don't
});
});
React component save function:
_onSaveClicked = (data) => {
this.context.testService.saveData(data)
.then(response => {
console.log('I\'m in then() block.');
console.log('response', response.data);
});
};
Service:
export default class TestService {
saveData = (data) => {
console.log('I\'m in services saveData function');
return Promise.resolve({data: data});
};
}
I see only "I'm in services saveData function" in my console.
How to make it works? I need to immitate server response.
Thank you for your time.
You can wrap your testing component in another one like:
class ContextInitContainer extends React.Component {
static childContextTypes = {
testService: React.PropTypes.object
};
getChildContext = () => {
return {
testService: {
saveData: (data) => {
return {
then: function(callback) {
return callback({
// here should be your response body object
})
}
}
}
}
};
};
render() {
return this.props.children;
}
}
then:
<ContextInitContainer>
<YourTestingComponent />
</ContextInitContainer>
So your promise will be executed immediately.