Being new to Angular 2+, I understand that I may not be approaching this the correct way. My issue involves two sibling components. When clicking on a "link" in one component, it redirects to another controller. My goal is to pass an object to the component that I am landing on.
This is my current approach:
In the first component (building list), I have an event:
public onClick_building(building: Building) {
this._building.addBuilding(building);
this._router.navigate(['/sam/checklistsam']);
}
The addBuilding method resides in a service called Building Service:
// Building Service
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptionsArgs, Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class BuildingService {
public newBuildingIdSubject: Subject<Building> = new Subject<Building>();
private _url = 'building/';
constructor(private http: Http, private _server: ServerService) { }
public addBuilding(building) {
this.newBuildingIdSubject.next(building);
}
}
Then, in the component (work with single building page) that I am redirected to:
// ChecklistComponent
import { Component, AfterViewInit, OnInit } from '@angular/core';
import { Building } from '../../../interfaces/building';
import { BuildingService } from '../../../services/building-service/building.service';
import { ServerService } from '../../../services/server-service/server.service';
@Component({
selector: 'app-checklist',
templateUrl: './checklist.component.html',
styleUrls: ['./checklist.component.css'],
providers: [BuildingService, ServerService]
})
export class ChecklistComponent implements AfterViewInit, OnInit {
public building: Building;
constructor(private _building: BuildingService) { }
ngOnInit() {
this._building.newBuildingIdSubject.subscribe(res => {
this.building = res;
});
}
However, 'this.building' is undefined. It seems like it doesn't enter the subscribe function during debugging.
Is there a better way to achieve this or am I overlooking something?
Thank you in advance!