I'm trying to use promise in order to connect user on my Ionic App.
I tried many things... but that doesn't work. What's the problem ? Can you help me please ?
I have to execute my load function before verify "access".
This is my code currently. What's wrong ? (Currently, the error is : "A function whose declared type is neither 'void' nor 'any' must return a value.")
This is my load function (no problem whith it, it's what I must execute in first)
load(credentials)
{
let headers : any = new HttpHeaders({ 'Content-Type': 'application/json' }),
options : any = { "pseudo" : credentials.email, "mdp" : credentials.password },
url : any = "http://localhost:8888/authVerif2.php" ;
return new Promise((resolve) => {
this.http
.post(url, JSON.stringify(options), headers)
.subscribe(data => {
console.dir(data);
this.infosUser = data;
//console.log(this.infosUser[0].prenom);
resolve(this.infosUser);
},
(error : any) =>
{
console.dir(error);
});
})
}
This is my login function :
public login(credentials) : Observable<any>{
this.load(credentials)
.then( a =>
{
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
// At this point make a request to your backend to make a real check!
let access = (credentials.password === "pass" && credentials.email === "email");
this.currentUser = new User('Simon', 'saimon#devdactic.com');
observer.next(access);
observer.complete();
});
}
}
);
}
these two functions are in a provider named "auth-service".
This provider is use in my page "login.html"
public login() {
this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
this.nav.setRoot(HomePage);
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
Do not stringify options beacause you have to post data to your login function in object format, if you stringify the options ,it means you are posting a string. so, you can't access data in login function from credentials.email & credentials.password
Related
I have this error :
Property 'sendEmailVerification' does not exist on type 'Promise<User>'.ts(2339)
my code :
// Send email verfificaiton when new user sign up
SendVerificationMail() {
return this.afAuth.currentUser.sendEmailVerification()
.then(() => {
this.router.navigate(['verify-email-address']);
})
}
I don't know the origin of the error and what am I missing?
You'll need to wait until the promise resolves:
SendVerificationMail() {
return this.afAuth.currentUser.then((user) => {
return user.sendEmailVerification();
}).then(() => {
this.router.navigate(['verify-email-address']);
})
}
I have the function below I have implemented and deployed to my cloud functions in my firebase project but upon execution, it causes me an error in the function log of the firebase console;
> TypeError: Cannot read property 'profileImgUrl' of undefined
I understand the meaning of the error it generates, but I don't understand why my user variable will be undefined
Here is the function below:
exports.eventInvites = functions.firestore
.document('Events/{eventId}').onCreate((snap, context) => {
const eventData = snap.data();
const eventId = context.params.eventId;
const invitees = eventData.invitees;
let user;
db.doc(`Users/${eventData.createdBy}`).get().then(doc => {
var data = doc.data();
user = data; // updated user data but still get undefined
return user;
}).catch(error => {
console.log(error.message);
});
if (invitees !== undefined || invitees.length > 0) {
invitees.forEach(invitee => {
db.collection('Users').doc(invitee).collection('feed').doc().set({
date: new Date(),
image: user.profileImgUrl, // error occurs here, says user is undefined
summary: `${user.firstName} ${user.lastName} invited you to an event`,
extraText: `${eventData.eventName}: ${eventData.eventDetails} `,
extraImages: [
eventData.eventImgUrl
]
}).catch(error => {
console.log(error.message)
});
});
}
});
get() is asynchronous therefore the code after it is getting executed before. To solve this, you can put all the code inside get():
db.doc(`Users/${eventData.createdBy}`).get().then(doc => {
var data = doc.data();
user = data;
if (invitees !== undefined || invitees.length > 0) {
invitees.forEach(invitee => {
db.collection('Users').doc(invitee).collection('feed').doc().set({
date: new Date(),
image: user.profileImgUrl,
summary: `${user.firstName} ${user.lastName} invited you to an event`,
extraText: `${eventData.eventName}: ${eventData.eventDetails} `,
extraImages: [
eventData.eventImgUrl
]
})
});
}
return user;
}).catch(error => {
console.log(error.message);
});
In the following code, consider each switchMap as step.
Step 1 : Create user if not already available
Step 2 : Create conversation
Step 3 : Return Response or Error
We might get business side exception in step 1 or step 2 and would like to handle it elegantly. Do we have better way of handling this ? e.g. Just skip step 2 if we get error in step 1. We tried a lot but not able to get better solution. If we simply throw error in step 1
Observable.throw(error)
automatic unsubscribtion is happening.
const createNewConversationEpic: Epic<Action<{}>, RootState> = (
action$: ActionsObservable<Action<Conversation | User | Error>>
) => {
return action$
.ofType(ConversationsActions.CREATE_NEW_CONVERSATION).pipe(
switchMap((action: Action<User>) => {
return action.payload.id
? Observable.of(action.payload)
: createNewLead(action.payload).pipe(
map(data => data),
catchError(error => {
return Observable.of(error);
})
);
}),
switchMap((response) => {
if (!(response instanceof Error)) {
return createNewConversation({ userId: response.id.toString() }).pipe(
map(data => ConversationsActions.CreateNewConversationSuccess(data)),
catchError(error => {
return Observable.of(error);
})
);
} else {
return Observable.of(response);
}
}),
switchMap(response => {
if (response instanceof Error) {
return ActionsObservable.of(
ConversationsActions.CreateNewConversationError(response),
ConversationsActions.MessagingGlobalError(response),
ConversationsActions.ResetMessagingGlobalError()
);
} else {
return Observable.of(response);
}
})
);
};
export const createNewLead = (body: {}) => {
return request('/api/v1/lead/create/mobile', AjaxMethod.POST, body);
};
const request = (path: string, method: AjaxMethod, body: {}) => {
const url = path;
return ajax({
body,
headers: {
Authorization: 'Bearer ' + getAuthToken(),
'Content-Type': 'application/json'
},
method,
responseType: 'json',
timeout: 120000, // 2 min
url
})
.map(e => {
console.log('[AJAX] Status --- ' + e.status);
console.log(e.response);
return e.response;
})
.catch(err => {
console.log(err);
let error = 'Error while executing request';
if (err.status === 400 || err.status === 412) {
if (err.response.error) {
error = err.response.error;
} else {
error = err.response.message;
}
}
// Handle 401 Status
if (err.status === 401) {
clearLocalstorage();
window.location.href =
window.location.origin +
'/authentication/?src=' +
window.location.pathname;
}
if (err.status === 403) {
error = 'Oops! Looks like you don\'t have access to it';
}
return Observable.throw(new Error(error));
});
};
If you need to halt the automatic unsubscribe, you just need to wrap the pipeline that you expect to have an error in another stream that can handle the exception, just like you would a standard try/catch, as long as you capture the error and handle it before returning to the outer stream the parent subscription remains intact.
const createNewConversationEpic: Epic<Action<{}>, RootState> = (
action$: ActionsObservable<Action<Conversation | User | Error>>
) => {
return action$
.ofType(ConversationsActions.CREATE_NEW_CONVERSATION).pipe(
// Parent Stream
switchMap((action: Action<User>) =>
// Start child stream
iif(() => action.payload.id,
Observable.of(action.payload),
createNewLead(action.payload)
).pipe(
// Process event as a "happy-path" since errors get forwarded to the end
switchMap((response) => createNewConversation({ userId: response.id.toString() })),
// Move this inline with the rest of the inner pipe line.
map(data => ConversationsActions.CreateNewConversationSuccess(data)),
// Catch all errors from this inner pipeline this will stop them from
// propagating to the outer stream.
catchError(e => ActionsObservable.of(
ConversationsActions.CreateNewConversationError(e),
ConversationsActions.MessagingGlobalError(e),
ConversationsActions.ResetMessagingGlobalError()
)
)
)
};
I''m totally new to AngularJS and NodeJs. I'm having a promise and it works well. There's console.log here ,this works well in server console.I need to print this console.log into client side (It's in Angular JS).
This is my server side code.
function checkNamesAvailable(
name /* : string | void */,
) /* :Promise<Object[]> */ {
const connection = createConnection()
return new Promise((resolve, reject) => {
const sql =
`SELECT names
FROM Names
WHERE JSON_EXTRACT(names, '$.name') = ? `
const values = [name]
const query = connection.query(sql, values, (error, results, fields) => {
connection.end()
if (error) {
return reject(error)
console.log(error)
}
resolve(results)
})
})
.then((results) => {
if(results.length > 0){
console.log("name is already exist")
}else{
saveNewName(names)
}
})
}
I'm calling above function in index.js as follows
addresses.post = function (
request /* : Object */,
response /* : Object */
) /* : Promise<Object> */ {
return authentication.authenticate((request.headers || {}).authorization)
.then((authorised) => {
if (!authorised) {
return Promise.reject(boom.forbidden('You do not have access to add new names'))
}
libAddr.checkNamesAvailable(request.body.data.attributes.names)
.then(() => {
return response.setStatusCode(200).setPayload({
})
})
.catch(err => {
return response.setStatusCode(400).setPayload({
message: err
})
})
Could someone help me regarding this?
You need to send your error message to client.
As like:
res.status(500).send({ error: 'Something failed!' });
And inside your AngularJS controller, you need to catch this error. For example:
$http.get('/url')
.then(function(result){
console.log('good!');
})
.error(function(error){
$scope.myErrorMessage = error.error;
});
And now you can show it on the page
<div ng-if="myErrorMessage">{{ myErrorMessage }}</div>
Please check the below code snippet:
addresses.post = function (
request /* : Object */ ,
response /* : Object */
) /* : Promise<Object> */ {
return authentication.authenticate((request.headers || {}).authorization)
.then((authorised) => {
if (!authorised) {
return Promise.reject(boom.forbidden('You do not have access to add new names'))
}
libAddr.checkNamesAvailable(request.body.data.attributes.names)
.then((results) => {
return response.setStatusCode(200).setPayload({
data: results
});
})
.catch(err => {
return response.setStatusCode(400).setPayload({
message: err
});
})
I'm new to Ionic and Angular, and coming from years of .NET development. I'm trying a few examples online to build login prototype with Ionic 2.
I got WebAPI working in the background simply returning JSON true or false depending if credentials passed is correct or not.
I got authentication provider looking like this:
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
this.result = this.http.post(this.CONST.APIUrl, JSON.stringify(credentials), new RequestOptions({headers: this.contentHeader})).map(res => res.json())
if (this.result)
{
this.currentUser = new User('Simon', 'saimon#devdactic.com');
}
return this.result;
}}
and login page looking like this:
public login() {
this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
setTimeout(() => {
this.loading.dismiss();
this.nav.setRoot(HomePage)
});
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
At the moment it always logs person in. I understand that this is happening because this.result always has a value. But how would I check data returned from the API before allowing person to login?
You can use Observable.do to create side effects for an Observable.
In login function:
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
this.result = this.http.post(this.CONST.APIUrl,
JSON.stringify(credentials), new RequestOptions({headers: this.contentHeader}))
.map(res => res.json())
.do(userData=>{
//check userData and set current user
this.currentUser = new User('Simon', 'saimon#devdactic.com');
return userData;//make sure to return the value to subscribe
});
return result;
}}