Zvi Vered
Zvi Vered

Reputation: 613

Angular8 routing : force all children to run their constructor, ngOnInit

I have the following routing:

const routes: Routes = [
  {
    path: '', children: [
      {path: '', pathMatch: 'prefix', redirectTo: 'timing'},
      {path: 'timing', component: TimingComponent},
      {path: 'fio', component: FioComponent},
      {path: 'rsp', component: RspComponent}, 
    ]
  }
];

I have a global service that opens a file and has to display data from this file to all the children. But at this point, only 'timing' is alive. 'fio','rsp' are undefined.

Is it possible to make 'fio','rsp' to run also ? In the global service I tried:

this.router.navigate(['/timing']).then(()=>{
        this.timing.UpdateView (val.Root.Timing);
        this.router.navigate (['fio']).then (()=>{ 
          this.fio.UpdateView (val.Root.Fio);
        })

But this does not work.

Thank you in advance, Zvika

Upvotes: 0

Views: 151

Answers (1)

Mises
Mises

Reputation: 4603

This is how you inject data downloaded by some.service.ts file in multiple components.

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [MyService], // provide service
  bootstrap: [AppComponent]
})
export class AppModule { }

Service is just an example that im creating variable inside to hold data there.

my.service.ts

@Injectable()
export class MyService {

    data: Observable<any>

    getData() {
        this.data = this.http.get() // http call to get data or other way to get data.
    }
}

app.component.ts

export class AppComponent {

  constructor(private myServ: MyService) {}

  ngOnInit() {
    this.myServ.getData() // Calling function to load data
  }
}

Example child components:

export class FioComponent {

  data$: Observable<any>

  constructor(private myServ: MyService) {} // when injecting service there have to be private, public or protected statement.

  ngOnInit() {
    this.data$ = this.myServ.data
  }
}

Upvotes: 1

Related Questions