Angular 12: reload header after login/ any navigation - javascript

I have angular application. In header I need to show notifications after user login like facebook , the notification unread count and on click notifications messages. Also after login need to redirect to timeline. onSubmit function in header ts file calls on login form submit.
header TS
ngOnInit() {
if (this.isLoggedIn) {
this.GetNotifications();
}
}
get isLoggedIn() {
return this.authService.isLoggedIn();
}
onSubmit() {
this.authService
.login(this.f.email.value, this.f.password.value)
.subscribe(
(data) => {
if (data["status"] === true || data["count"] === true) {
window.localStorage.setItem(
"myUser",
JSON.stringify(data["data"])
);
window.localStorage.setItem("isLoggedIn", "true");
this.router.navigate(["timeline"]).then(() => {
window.location.reload();
});
} else {
window.localStorage.setItem("isLoggedIn", "false");
}
},
(error) => {
window.localStorage.setItem("isLoggedIn", "false");
}
);
}
Auth service Ts
login(email: string, password: string) {
let input = new FormData();
const headers = { 'APP-TOKEN': 'xxxx' };
input.append('email', email);
input.append('password', password);
return this.http
.post<any>(`${this.serverUrl}api/v1/login`, input, { headers: headers })
.pipe(
map((user) => {
if (user && user.token) {
localStorage.setItem('myUser', JSON.stringify(user));
}
return user;
}),
catchError(this.handleError)
);
}
isLoggedIn() {
if (localStorage.getItem('myUser')) {
return true;
}
return false;
}
The problem is without window.location.reload(); the count/notification data not shows in header. After login, it needs reload after navigation to timeline. But window.location.reload(); gives me problem on production so I have used useHash: true in app-rounting.module.ts. Again that giving me problem in SSR implementation. So I need alternate way for reloading header after every navigation. As if I go to another header menu there also I need to use window.location.reload(); to show notification data in header.
I have tried this way. But not works as expected in above flow.
How I can get rid of window.location.reload(); and get same functionality/get notification data after navigation in angular without using window?
Please help and guide.

Related

When I go back and forth from the page it doesn't send post requests

I have a component where I list the policies. For example, when I come to the payment screen of the "A" policy, I send a post request. I can view the installments of policy "A". Then i go back by pressing back button in browser and go to the payment screen of policy "B". I see the installments of the "A" policy on the screen that comes up. If we refresh the page it send a post request and I can view the installments of policy "B". How do I send the post request without refreshing the page?
service
const getAsosPaymentInfo = (getPolicyAccountInfoRequestDto) => {
return new Observable((observer) => {
axiosInstance
.post(SERVICE_PATH + '/getAsosPaymentInfo', getPolicyAccountInfoRequestDto)
.then((response) => {
observer.next(response.data);
observer.complete();
})
.catch((err) => {
console.log(err);
});
});
};
component
const { paymentInfoData, setPaymentInfoData } = useContext(PaymentInfoDataContext);
useEffect(() => {
if (Object.keys(paymentInfoData).length === 0 && props.location.state.policy.isActive === true) {
PolicyService.getAsosInstallments(
{
policyNumber: props.location.state.policy.policyNumber,
renewalNumber: props.location.state.policy.renewalNumber,
policyTypeExtCode: props.location.state.policy.policyType.extCode,
productTypeExtCode: props.location.state.policy.productType.extCode
}
).subscribe(
(response) => {
setPaymentInfoData(response);
}
);
}
}, []);
For performance optimization, React Navigation avoids mounting the screen every time the user revisited it. you need to listen to the screen focus event and then run your logic there.
React Navigation provides a hook which work with normal useEffect
import {useIsFocused, useNavigation} from '#react-navigation/native';
// Some where inside screen
const { paymentInfoData, setPaymentInfoData } = useContext(PaymentInfoDataContext);
const isFocused = useIsFocused()
useEffect(() => {
if (Object.keys(paymentInfoData).length === 0 && props.location.state.policy.isActive === true) {
PolicyService.getAsosInstallments(
{
policyNumber: props.location.state.policy.policyNumber,
renewalNumber: props.location.state.policy.renewalNumber,
policyTypeExtCode: props.location.state.policy.policyType.extCode,
productTypeExtCode: props.location.state.policy.productType.extCode
}
).subscribe(
(response) => {
setPaymentInfoData(response);
}
);
}
}, [isFocused]);

Login still redirect to the same page even when using different email to log in

I'm using Firestore and Nuxt for my project.
I want my application to redirect the pages based on their user type when they are logged in.
I want if userType = contractor, when login it will redirect to /WPC/DashboardWPC.
I want if userType = subcontractor, when login it will redirect to /Form/SectionA.
But currently, when logging in, it will always redirect to /Form/SectionA. I don't want that. I want it to log to different pages based on their user type.
Any advice?
Login() {
let credentials = {
email: this.email,
password: this.password,
};
this.$store
.dispatch("user/Login", credentials)
.then(() => {
const users = firestore.collection('Users')
users.get().then(() => {
if (firestore.collection('Users').where("userType", "==", "subcontractor")) {
window.location = "/Form/SectionA";
} else if (firestore.collection('Users').where("userType", "==", "contractor")) {
//console.log(snapshot.docs[0].data())
window.location = "/WPC/DashboardWPC";
} else {
window.location = "/BWG/DashboardBWG";
}
})
}).catch((err) => {
alert(err.message)
})
}
I am unsure how are you allowing your users to log in, but the signInWithEmailAndPassword is the method Firebase provides.
I have no experience with nuxt.js but something like this should give you a general idea:
Login() {
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then((user) => {
const _userDoc = firestore.collection('Users').doc(user.uid).get();
const userType = _userDoc.data['userType'];
if(userType == "subcontractor"){
window.location = "/Form/SectionA";
}
else if(userType == "contractor"){
window.location = "/WPC/DashboardWPC";
}
else{
window.location = "/BWG/DashboardBWG";
}
},
(err) => {
alert(err.message);
},
);
}
Also, for registering your users you can use the createUserWithEmailAndPassword method.

Redirect after logging in with $auth in nuxtjs

I'm having trouble redirecting my user when logging in with nuxt's default $auth configuration. Here's my problem:
Whenever I log in using the laravel/jwt provider, it redirects to my website home.
I have several points on the site where I need to open a modal with my login and I need to keep the user logged in on the same page he is on.
But I already tried to follow the documentation using the fake redirect flag and still I couldn't.
Is there any way to log in, if he is not on a specific page, such as the login page, he just refreshes instead of redirecting to the / route?
My usage:
async login() {
try {
this.loading(true)
await this.$auth.loginWith('laravelJWT', { data: this.form })
if (!this.redirectHome) {
this.$router.back()
this.$emit('is-logged')
}
} catch (error) {
this.loginError = true
} finally {
this.loading(false)
}
},
My resolution:
async login() {
await this.$auth
.loginWith('laravelJWT', { data: this.form })
.then(() => {
this.loading(true)
if (this.$route.name !== 'login') {
this.$router.go(this.$router.currentRoute)
}
this.$emit('is-logged')
})
.catch(() => {
this.loginError = true
})
.finally(() => {
this.loading(false)
})
},
use this.$auth.options.redirect = false before loginWith it will disable redirect.
when the promise resolved then you can call other api to refresh data or do whatever you want.

Ionic 4 firebase phone-authentication redirect new users to particular page

I am using firebase phone-authentication in my ionic 4 app. I have successfully implemented jwt authentication. If the token is available I redirect users to the main page else redirecting to the login page.
But here comes the problem on the login page. If the user is new(coming for the first time) then I want to redirect to the details page to get some other data like email, name, else (old user) redirect to the main page.
The problem is I don't have different buttons for login and signup in my app. The same login is used for both login and register
What is the best solution to check if the user is new or old? The last solution is to check the user in the database and redirect accordingly.
Here is my code
authentication.service.ts
authenticationState = new BehaviorSubject(false);
constructor(private storage: StorageService, private plt: Platform, private router: Router) {
this.plt.ready().then(() => {
this.checkToken();
});
}
checkToken() {
this.storage.get(TOKEN_KEY).then(res => {
if (res) {
this.authenticationState.next(true);
}
})
}
login() {
return this.storage.set(TOKEN_KEY, 'Bearer 1234567').then(() => {
this.authenticationState.next(true);
});
}
logout() {
return this.storage.clear().then(() => {
this.authenticationState.next(false);
this.router.navigate(['home'])
});
}
isAuthenticated() {
return this.authenticationState.value;
}
app.component.ts
constructor(private authenticationService: AuthenticationService){
this.authenticationService.authenticationState.subscribe(state => {
if (state) {
this.router.navigate(['menu/items']);
} else {
this.router.navigate(['home']);
}
});
}
home.page.ts
if(old user) {
// redirect to main page
}
else {
redirect to details page
}

Angular Firebase Cloud returns incorrect data

I have a problem with Angular 8 and the Firebase cloud database. If I get my user document initially it is correct. Then I call some logic which only changes some values but not all. Then I reload the user but some of the values are not correct even if they are not updated. It is really strange and I do not know why this happens. Here is my code snippet:
// if the user is set return the user, if not set get user from firebase, if withRefresh is true always refresh user
GetUser(withRefresh?: boolean): Observable<User> {
if (this.user == null || withRefresh) {
return this.authService.GetUser().pipe(map(user => {
console.log(user);
this.user = user;
return this.user;
}));
} else {
return of(this.user);
}
}
AuthService:
GetUser(): Observable<User> {
return this.afAuth.authState.pipe(switchMap((user) => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
this.LogOut();
}
}));
}
This is in my dashboard where I call the first GetUser method:
SyncActivities() {
this.appStore.GetUser().pipe(take(1)).subscribe((user) => {
if (this.appStore.user != null) {
this.syncActivitiesService.Synchronize(this.appStore.user);
}
});
}
At the end of my Snychronize function I reload the user and activities. This returns the wrong values.
if (i === activities.length - 1) {
this.appStore.GetUser(true).pipe(take(1)).subscribe(() => {
this.appStore.GetUserActivities(true);
});
}
On the Firebase Cloud the data is correct.
console log correct
console log incorrect

Categories

Resources