Sending user to the login page in order to authenticate before allowing them to send a message to the admin

Before a user can post a message in the message form, they must first be logged in. If not, when they click the send message button, they will be redirected to the login page.

I attempted using route guards, but unfortunately, they are guarding all of the components!

Below is the HTML section:

<div class="modal-body">
    <form role="form" #f="ngForm">
        <!-- Validation email -->
        <div class="form-group">
        </div>
        // Other form input fields...
        <button type="submit" class="btn btn-success pull-right" (click)="sendMsg(f)">Send Message!</button>
    </form>
</div>

Here is the TypeScript portion:

sendMsg(f: NgForm) {
if(this.loginService.loggedIn()){
const msg: Message = f.value;
msg.lu = false;
// Additional logic here
}
else{
  alert('Please log in before sending a message');
  this.router.navigate(['/login']);
}  

In the app-routing module, I have used canActivate:[AuthGuard], which directs the user to the login page if they attempt to access the component. My goal is for the user to access the component and only be redirected to the login page when clicking the send message button.

Answer №1

Instead of using the canActivate:[AuthGuard] in the routing module, consider implementing a login check within the SendMsg() method.

import { Router } from '@angular/router';
constructor(private router: Router){
}
sendMsg(f: NgForm) {
let loggedIn : boolean = false;
loggedIn = //set this to true if the user is logged in
if(loggedIn)
//include your existing logic for posting a message
}
else{
this.router.navigate(['/login']); //redirect to the login page if not logged in
}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to verify whether a checkbox is selected and store the status in the LocalStorage

Hey there, I'm still new to the world of programming and currently just a junior developer. I have a list of checkboxes and I want to save any unchecked checkbox to my local storage when it's unselected. Below is a snippet of my code but I feel l ...

Closing Accordions Automatically

Hello everyone! I'm currently working on a NextJS project and facing an issue with my dynamic accordion component. I'm using typescript, and the problem lies in only one accordion being able to open at a time. How can I ensure that only the spec ...

Proceed to the subsequent 'then' statement promptly

I'm currently delving into Typescript and exploring functional programming. My project involves a simple process where I query MongoDB, then for each document retrieved, I make a call to SQL Server to fetch additional data. Here is the snippet of code ...

Having trouble setting the InnerHTML property of Null on my Ionic app, what could be the issue?

I'm working on a code to display the remaining time for generating a random code in the DOM. var count = setInterval(function () { var date = new Date(); var currentSecond = date.getSeconds(); ...

Typescript error encountered when executing multiple API calls in a loop causing Internal Server Error

I'm relatively new to Typescript/Javascript and I am working on a function called setBias(). In this function, I want to set all indices of this.articles[i].result equal to the biased rating returned by the function getBiasedRating(this.articles[i].ur ...

What is the alternative parameter to use instead of onChange in React Router v4?

Having an issue with the onChange Prop in TypeScript and React JS: I am encountering an error message saying "No overload matched this call." <HashRouter> <Switch> <Route path="/" ...

A guide on updating the button color in Bootstrap using Angular

I am trying to implement a feature where the button changes color based on user input. For example, when the user enters 2 figures, the button should turn blue instead of its default red color. How can I achieve this using Bootstrap and Angular? This is w ...

A simple trick to compile and run TypeScript files with just one command!

Converting TS to JS is typically done using the tsc command, followed by executing the resulting .js file with node. This process involves two steps but is necessary to run a .ts file successfully. I'm curious, though, if there is a way to streamlin ...

Unable to locate node.js (although it is installed) while building the default Angular project in Visual Studio 2019

In my Visual Studio 2019, I created a default Angular project combined with .NET Core 3.0. After building and running the project, an error message appeared: error : Node.js is required to build and run this project. To continue, please install Node.js f ...

Export a TypeScript type dynamically

I'm currently developing an application and I have a query regarding dynamically exporting a type. My API call retrieves a list of categories. const getCategories = async () => { const fetchedCategories = await axios.get(uri) // Expected outp ...

Encountered a NodeJS error while attempting to locate information in a mongo DB: UnhandledPromiseRejectionWarning

In my MEAN stack application, I am working on implementing a login feature that includes social login functionality. When a new user attempts to log in using Facebook, I need to verify if their Facebook account is already registered in my MongoDB database. ...

Validating Emoji Inputs in Angular

Is there a way to validate input for Emoji and display an error message if invalid? The form field in question is: 'name': new FormControl('', [Validators.required]), ...

The array contains data, yet the console is displaying a length of 0 for the array

I’m experiencing an issue with my code that involves a files array. Whenever I add a new file, it displays the incorrect length of the array. Strangely, if I use setTimeout to check the length, it shows the correct one. console.log('row.myDocuments ...

Unlock the full potential of ngx-export-as options with these simple steps

Being a newcomer to angular, I am currently working with a datatable to display a set of data. I have successfully implemented the functionality to export the table's data as a PDF using ngx-export-as library. However, when downloading the PDF, it inc ...

Is there a way for me to customize the clickable region of my checkbox?

I'm facing a formatting issue in my Angular application that I need help with. The problem lies in the clickable area around my checkboxes, as shown in the images linked below. https://i.sstatic.net/MoLYZ.png https://i.sstatic.net/2VT5x.png What I a ...

Cannot locate module in Jest configuration

I'm struggling to understand config files and encountering issues while attempting to run jest unit tests: Cannot locate module '@/app/utils/regex' from 'src/_components/DriverSearchForm.tsx' Here's my jest configuration: ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

Have you made a selection in both bi-directional bound select dropdowns?

I have implemented two-way binding on select dropdowns using ngFor, and they are functioning correctly. However, upon page load, no option is selected by default. I attempted to use [selected] but it did not work... Any ideas on how to resolve this? Code: ...

Utilizing Angular Material's <mat-selection-list> and <mat-list-option> components seamlessly between different sections of a template

How can a <mat-list-option> declared in component sub subscribe to a <mat-selection-list> outside of component sub (for example, in component app)? (Unfortunately, I couldn't get Stackblitz to work due to my corporate's proxy restric ...