Search code examples
angularangular-routingangular-router

Route on components Angular


Can i route on components to specific page? i would like to route somewhere after like() process done

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, RouterModule, Routes } from '@angular/router';
import { GamesService } from '../games.service';
import { IGames } from '../games';

  constructor(private router:Router, public route:ActivatedRoute, private gs:GamesService) { }

  like(id:string,l:string){
    if(l == 1){this.likes=0 }else{this.likes=1};
    this.gs.like(id,this.likes).subscribe(
      (data)=>{
        // this.game=data;
        console.log(data);
         router.navigate(['wishlist'];
      }
    );
  }

i got this error messsages

Error: Can't resolve all parameters for DetailComponent: (?, [object Object], [object Object]).

Solution

  • The component where you have the like method (let's name that component as Abc)

    abc.component.ts

    import { Router } from '@angular/router';
    
    constructor(private router: Router) {
    }
    
    like(id:string,l:string) {
        if (l == 1) {
            this.likes=0;
        } else {
            this.likes=1;
        }
        this.gs.like(id,this.likes).subscribe((data) => {
           console.log(data);
           router.navigate(['otherComponentPath']); add this
        });
    }
    

    abc.module.ts

    import { RouterModule } from '@angular/router';
    import { AbcComponent } from '<path to the component>';
    import { AbcRoutingModule } from '<path to the abc routing module>';
    
    @NgModule({
        imports: [
            ...,
            RouterModule,
            AbcRoutingModule,
        ],
        declarations: [ 
            AbcComponent,
            OtherComponent 
        ]
    })
    export class AbcModule {
    }
    

    abcRouting.module.ts

    const routes: Routes = [
        ...
        path: 'otherComponentPath', //this will be in the url
        component: OtherComponent
    ];
    
    @NgModule({
        imports: [ RouterModule.forChild(routes) ],
        exports: [ RouterModule ]
    })
    export class AbcRoutingModule {
    }