I am trying to use web api call get method to access data and display in my page. My url would be something like: https://localhost:44399/api/APIOrder/GetUserOrder?email=xxx#gmail.com to be able to display the data.
However, when I combine my url with a variable,it doesn't display anything and console log shows the url in https://localhost:44399/api/APIOrder/GetUserOrder?email=[object Promise]. Is there any way to let the url read my this.User variable?
please review my getUserOrder()
User = this.storage.get('currentUser');
constructor(private http:Http,public storage: Storage){
}
public getUserOrder()
{
var url="https://localhost:44399/api/APIOrder/GetUserOrder?email=";
console.log(url+this.User);
return this.http.get(url+this.User).map(res=>res.json());
}
I am really new to this. Pls tell me if i am unclear. Any help would be much appreciated..
UPDATE
It shows undefined because it accessed the variable value on top but not from ionViewWillEnter
User:string;
constructor(private http:Http,public storage: Storage){
}
async ionViewWillEnter()
{
this.User = await this.storage.get('currentUser');
}
public getUserOrder()
{
var url="https://localhost:44399/api/APIOrder/GetUserOrder?email=";
console.log(url+ this.User);
return this.http.get(url+this.User).map(res=>res.json());
}
You should await the return of the Promise. You can do this inside the constructor or inside a lifecyle like ionViewWillEnter()
User: string;
async ionViewWillEnter() {
this.User = await this.storage.get('currentUser');
}
Answer here: "This is the expected result."
UPDATE
This is a different approach: if your function is directly called somehow, you can create a function which returns the variable from storage. If the data is found, proceed with the http request.
async getUserOrder() {
const user = await this.getUserFromStorage();
if (user) {
var url="https://localhost:44399/api/APIOrder/GetUserOrder?email=";
return this.http.get(url + user).map(res=>res.json());
}
}
async getUserFromStorage(): Promise<string> {
return await this.storage.get('currentUser');
}
Related
I try to use the Ionic Storage module to store some values, for example my authentication token :
/**
* Get Token
*/
public get token(): string {
this.storage.get(this.LS_TOKEN).then((val) => {
console.log(val);
this._token.next(val);
console.log( this._token.getValue());
});
return this._token.getValue();
// return 'testtttt';
}
I try multiple things, return directly the value, set the value and return the variable...
But I always got a null, and the thing that is strange is that if I return a string directly it works, when I console.log the val it show the string that I want, but the return is always null..
What am I doing wrong ?
Edit :
In response of the first answer I have tried this :
/**
* Get Token
*/
public get token() {
this.tokenPromise().then(yourToken => {
console.log(yourToken);
return yourToken;
});
}
public tokenPromise() {
return new Promise((resolve, reject) => {
this.storage.get(this.LS_TOKEN).then((val) => {
resolve(val);
}).catch(ex => {
reject(ex);
});
});
}
My problem is the same, in my components when I try to use : console.log(this.sharedService.token);
It's still null
It is not working with your new token() method.
It is still asnychron. Im gonna show you:
public get token() {
return new Promise((resolve, reject)=>{
this.storage.get(this.LS_TOKEN).then((val) => {
resolve(val);
}).catch(ex=>{
reject(ex);
});
});
}
Now you can use your token from the sharedservice like this:
this.sharedService.token.then(token=>{
//use token here;
});
or you can use await, but the function who is calling it, must be async:
async useTokenFromService(){
let token = await this.sharedService.token;
console.log(token);
}
You are getting a Promise from the storage.get() method.
This means it is running asynchron.
You can return Promise.
public get token() {
return new Promise((resolve, reject)=>{
this.storage.get(this.LS_TOKEN).then((val) => {
resolve(val);
}).catch(ex=>{
reject(ex);
});
});
}
And you can receive this with an async function and await the result:
async loadToken(){
let loadedToken = await this.token();
// use your loadedToken here...
}
Or you can use the .then method from the promise like this:
loadToken(){
this.token().then(yourToken=>{
// use the token yourToken here...
});
}
I'm having difficulty getting data with subscribe in the constructor of an Ionic page, basically I need to do the subscribe to get a list and show to the user, but I get undefinied
In my constructor, I do this:
this.getUser(this.auth.currentUser().uid);
console.log(this.user);
My getUser():
getUser(uid) {
const self = this;
this.auth.getUserData(uid).subscribe(function(doc) {
if (doc.exists) {
self.user = doc.data();
} else {
console.log("No such document!");
}
});
};
But, when i call other function with button, i get the data:
userf(){
console.log(this.user);
}
Obs: I use Firestore
The reason it gives you undefined is because your method “getUser” is async and when you call console.log the user value is not yet obtained.
So you should access user value inside your getUser method after it is received.
Now also you are trying to pass “this” into the getUser method with const. start using fat arrow functions which do not create their own scope (this):
getUser(uid) {
this.auth.getUserData(uid).subscribe((doc) => {
if (doc.exists) {
this.user = doc.data();
} else {
console.log("No such document!");
}
});
};
How to make multiple api calls with axios - when I have to pass a value from my first api response to all subsequent calls. I have 2 other calls to be made inside getData function where I have to pass a value from y first api response {data} - how to chain multipl requests with axios? 2 next calls are dependent on first call - they are not dependant on each other - they can happen in parallel - the only issue I have is - I am not able to pass the response data to the subsequent end-points.
import Request from 'axios';
export function getData() {
return async function getData(dispatch) {
const { data } = await getDatafromService();
dispatch({ type: 'Data_fetch', payload: data });
};
}
async function getDatafromService() {
const endpoint = "api-url";
return Request.get(endpoint);
}
Something like this should work for an overall structure.
The async function getData will ultimately return an array of the responses from the last two requests.
import Request from 'axios';
export function getData() {
return async function getData(dispatch) {
const { data } = await getDatafromService();
return Promise.all([
sendDataToFirstService(data),
sendDataToSecondService(data),
])
};
}
function getDatafromService() {
const endpoint = "api-url";
return Request.get(endpoint);
}
function sendDataToFirstService(data) {
const endpont = "first-url";
return Request.post(endpoint, data)
}
function sendDataToSecondService(data) {
const endpont = "second-url";
return Request.post(endpoint, data)
}
Note that you may need to modify the data received from the original get request before passing it to the next two.
You can do this by chaining .then onto the Promise like so...
function getDatafromService() {
const endpoint = "api-url";
return Request.get(endpoint).then(({data}) => modify(data));
}
i have some screen, where i will call some url. But i know how to call the function using get and show the data.But now i want to send the parameter with url.
here my url.i need to send the parameter :
this.passingdata = { CatID: "2" };
This above parameter i need to send to below get url function
constructor(public viewCtrl: ViewController, public modalCtrl: ModalController, private http: Http, public loadingCtrl: LoadingController) {
let that = this
let loader = this.loadingCtrl.create({
content: "Please wait..."
});
loader.present();
that.http.get('http://www.example.com/api/tackj.php').map((res) => res.json()).subscribe((data: any) =>{
that.questions = data.QuestionsList;
loader.dismiss();
})
}
ionViewDidLoad() {
let that = this;
that.slides.lockSwipes(true);
that.slides.enableKeyboardControl(false);
}
Thank in advance !!
If you want to pass some parameters most probably it would be a post method then you can pass data as second parameter to the http.post method. So you need to find out whether the API is post method or get method.
Refer this link
AngularJS passing data to $http.get request
I am new to Ionic 2 and Promises and having some issues.
My Ionic 2 app saves an auth_token to the local storage:
this.storage.set('auth_token', auth_token);
Then later in my secured component I want to check if a token is set, but I don't know how to do this.
I tried this:
authenticate() {
var auth_token = this.storage.get('auth_token').then((val) => {
return val;
});
}
Then from somewhere else I called:
console.log(this.auth.authenticate);
But it won't work, it just returns the function itself.
How do I return the token from my authenticate method?
Check here for chaining of promises.
In your authenticate() function return the original promise call and use then in the function in the other location
authenticate() {
return this.storage.get('auth_token').then((val) => {
return val;
});
}
When caling authenticate...
this.auth.authenticate().then((val)=>{
console.log(val);
}).catch(error=>{
//handle error
});
You just want to check or do you need to return it?
If it's only checking you can do this:
authenticate() {
this.storage.get('auth_token').then((val) => {
if(val){ ... } // or console.log it if it's just what you need.
}
}
If you need to return, create a promise like this:
authenticate = (): Promise<{exists: boolean, auth: any}> =>{
return new Promise<{exists: boolean, auth: any}>(res =>{
this.storage.get('auth_token').then((val) => {
if(val){
res({exists: true, auth: val});
} else {
res({exists: false, auth: val});
}
}
})
}
and later call authenticate().then(res =>{}) and access the object returned in res.
EDIT
As commented by Suraj and tested now, it doesn't need to be encapsulated inside a new promise, so if you need to return it just use the method Suraj suggested.