Unable to automatically redirect to portal upon submission of form

After successfully logging the user into my app, I want to redirect them imperatively to the portal page. However, when I use the router.navigate() function, a few things happen that are causing issues. First, the app redirects to /portal. Then, it immediately redirects again to /portal with Email Address and Password as query strings. Finally, it seems like the app "resets" in some way, forgetting that the user has already logged in, so it redirects back to the login page. What could be causing this problem?

All of this is happening within a form onSubmit event, triggered by this button:

<button type="submit" (click)="onSubmit(Form)">Sign in</button>

Here is the onSubmit code snippet:

public onSubmit(form: EmailForm): void {
    this.apiLogin.LoginUser(form.EmailAddress, form.Password).subscribe(
        (user: LoginUser) => {
            if(user.UserToken == null) {
                this.addValidationError("Invalid username and/or password.");
            }
            else {
                this.appState.setUser(user);
            }
        },
        (err) => {},
        () => {
            this.router.navigate(['/portal']);
        }
    );
}

Additionally, here is how my routes are set up:

const appRoutes: Routes = [
    { path: '', component: HomeComponent, pathMatch: 'full' },
    { path: 'portal', component: PortalComponent, canActivate: [AuthGuard] },
    { path: '**', component: PageNotFoundComponent }
];

Although not necessary, here is the AuthGuard service used on the portal route. Thanks to @Sasxa for assisting me in implementing this AuthGuard.

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private appState: ApplicationState, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        return this.checkLogin(url);
    }

    checkLogin(url: string): boolean {
        if (this.appState.User.UserToken) return true;

        this.navToLogin(url);
        return false;
    }

    private navToLogin(redirUrl: string) {
        this.router.navigate(['/']);
    }
}   // end class

Answer №1

After some troubleshooting, I was able to identify the issue. It turns out I mistakenly used (click) instead of (ngSubmit). Here's the corrected code:

(ngSubmit)="submitForm()"

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

Creating a custom grid drag and drop feature within Angular Material adds a dynamic element to your application, going beyond basic list

According to the angular material documentation, creating a pure grid drag and drop feature is not straightforward. One solution I have come up with involves using multiple horizontal lists where items can only be dragged within their own row, resulting in ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

Obtaining JSON Data from API using Angular 2 Http and the finance_charts_json_callback() Callback

Having trouble retrieving JSON data from this API: I'm unsure how to access the returned finance_charts_json_callback(). Currently, I am utilizing Angular 2's http.get(): loadData() { return this.http .get(this.url) .map((res) => ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

Ways to enable Urql (typescript) to accept Vue reactive variables for queries generated using graphql-codegen

I'm currently developing a Vue project that involves using urql and graphql-codegen. When utilizing useQuery() in urql, it allows for the use of Vue reactive variables to make the query reactive and update accordingly when the variables change. The ...

Tips for saving an Angular project for offline use

I have created a basic form for a family member to use in their medical practice, and I want to make it functional offline. The form simply captures data and displays it, with no need to send or store the information anywhere. What would be the most effect ...

Automatically upgrade packages to the latest version 12.0.0-next.0 with ng update

Recently, I've encountered an issue while updating my projects from Angular 10 to Angular 11. Whenever I run ng update, some packages are being upgraded to version 12.0.0-next.0 instead of the stable release. It seems like ng update is installing pre- ...

Retrieving attributes from a reactive object in TypeScript

I have a question regarding accessing values in Typescript. Whenever I load my website, I make a call to a service that fetches user data. private currentUserSource = new ReplaySubject<IUser>(1); currentUser$ = this.currentUserSource.asObservable ...

The Facebook provider is missing in Ionic Native

An error has occurred: No provider for Facebook!     InjectionError (core.es5.js:1231)     NoProviderError (core.es5.js:1269)     ReflectiveInjector_ ...

Creating a signature for a function that can accept multiple parameter types in TypeScript

I am facing a dilemma with the following code snippet: const func1 = (state: Interface1){ //some code } const func2 = (state: Interface2){ //some other code } const func3: (state: Interface1|Interface2){ //some other code } However, ...

Importing JavaScript into an Angular component: A beginner's guide

Within my Angular-11 project, I have included the following JavaScript file: "node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js", I have added it to the angular.json configuration as detailed above. import Stepper from '.. ...

Is it possible in Typescript to reference type variables within another type variable?

Currently, I am working with two generic types - Client<T> and MockClient<T>. Now, I want to introduce a third generic type called Mocked<C extends Client>. This new type should be a specialized version of MockClient that corresponds to a ...

Display or conceal an icon based on the data in the field

Can someone provide guidance on how to make an icon appear or disappear based on the logic within [ngIf]? The icon should only be displayed if there is information in a specific field. Should I implement this inside ngIF or in my TS file? Can the icon cl ...

Guide on customizing a dropdown button in a class-based Angular library with version 4 or higher

My dilemma revolves around utilizing the Angular Material library for a drop-down navigation bar. The issue at hand is my desire to hover through the list, yet I am unable to tweak the style within HTML. Fortunately, I can easily make alterations in Chrome ...

Receiving error in TypeScript while using the 'required' attribute in the input field: "Cannot assign type 'string | undefined' to parameter expecting type 'string'"

In my TypeScript code, I am currently in the process of transitioning from utilizing useState to useRef for capturing text input values. This change is recommended when no additional manipulation necessitating state or rerenders is required. While I have ...

Typescript error: The value "X" cannot be assigned to this type, as the properties of "Y" are not compatible

Disclaimer: I am relatively new to Angular2 and typescript, so please bear with me for any errors. The Challenge: My current task involves subtracting a start date/time from an end date/time, using the result in a formula for my calculation displayed as " ...

Utilizing material-ui with Autocomplete featuring various value and option types

In my code, I am looking to store only an option's ID in a value For autocomplete functionality, the value's type and the option's type need to be the same My solution was to change the value in onChange, which worked successfully However ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Angular 2 does not include Bootstrap CSS by default

Found this helpful tip at https://angular.io/docs/ts/latest/guide/forms.html Time to include the stylesheet you need. Go to your application's root folder in the terminal and run this command: npm install bootstrap --save In index.html, make sure ...

Change the color of the Parent Menu when a childMenu is clicked on using CSS and HTML

<li class="btn-group" mdbDropdown> <a mdbDropdownToggle id="ParentId"> <i class="nav-item"></i> MainMenu <i class="fa fa-angle-down"></i> </a> <div class=" ...