Angular 2 redirecting automatically using router.navigate

router.navigate() working fine in one case and redirecting to home page for another case.

app.module.ts

  const appRoutes: Routes = [
  { path: 'news/:urlLink', component: ArticlereaderComponent },
  { path: '', component: HomeComponent }
  ]

home.component.ts

  public forwardURL(urlLink: string) {   
       this.router.navigate(['news/' + urlLink]);
  }

article.reader.ts // It's coming here after routing

 constructor(public route: ActivatedRoute, public http: HttpClient) {
      this.route.params.subscribe(params => {     
       this.parameterLink = params.urlLink;   
      });
  this.getArticle();
  }

  public getArticle() {
  this.http.get(this.APIHost 
  /feed/FeedByUrl/"+this.parameterLink+"/").subscribe(data => {
  this.feed = data;     
  });

}

home.component.html

 <div class="row">
  <div class="col-sm-4" style="padding: 2px;" *ngFor="let Feed of TopStories" (click)="forwardURL(Feed.urlLink)">
    <div class="card card-inverse">
      <img class="card-img" src="{{Feed.headLineImage}}" alt="Card image">
      <div class="card-img-overlay">
        <div class="catagory">{{Feed.catagory}}</div>
        <p class="card-text">{{Feed.headline}}</p>
      </div>
    </div>
  </div>
</div>

It's working fine with this.

But the same (click)="forwardURL(Feed.urlLink)" used in other places in the same html page navigating but then redirecting to home page.

  <div class="list-group" *ngFor="let Feed of MostRead" (click)="forwardURL(Feed.urlLink)">
      <a href="#" class="list-group-item mostread list-group-item-action flex-column align-items-start">
        <div class="d-flex flex-row">
          <div class="d-inline-flex p-2">
            <img src="{{Feed.headLineImage}}" style="height: 67px;width: 70px;" alt="">
          </div>
          <div class="d-flex p-2">
            <p class="mb-1">{{Feed.headline}}</p>
          </div>
        </div>
      </a>
    </div>

Redirecting to home page for the above case , both this <div> are in a same page home.component.html

1 answer

  • answered 2018-04-17 05:19 Pankaj Parkar

    I guess, the anchor tag with href="#" is what creating problem for you. It tries to redirect to #(blank) route, but then you have /home as fallback route it redirects to /home.

    Remove href="#" from your anchor should solve the problem.