michali
michali

Reputation: 3822

angular 2 - subscribe function called twice

I have this code:

import { Component } from '@angular/core';
import { ViewService } from './view.service';
import { Router, ActivatedRoute, Params } from '@angular/router';


@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css'],
  providers: [ViewService]
})
    export class ViewComponent {

      constructor(viewService: ViewService, private route: ActivatedRoute) {

        this.route.params.map(params => params['id']).subscribe((id) => {
            console.log("id: "  + id);
        });

      }
    }

I have subscribed my code to the run parameters. The thing is - subscribe function is called twice - First time - id is undefined. Second time - id value exists.

What could be the cause for this issue?

Upvotes: 2

Views: 4963

Answers (1)

michali
michali

Reputation: 3822

The issue here was that my ViewComponent was loaded twice. that's why the constructor was called twice:

  1. In my app.module.ts when defining routing. here:

    RouterModule.forRoot([ { path: '', component: ViewComponent }

  2. in my app.component.html - I added <app-view> tag.

Upvotes: 4

Related Questions