Dealing with a parent component that has children routes, my goal is to share a project variable among them. The project value may change, and I need all route pages to reflect this change. Following the guide in the Angular 2 tutorial on achieving this, I encountered an issue when initializing my observable. Upon the first call, the value fails to display initially but shows up upon updates. The reason behind why the project variable lacks an initial value remains elusive. Any insights on this behavior and possible fixes are greatly appreciated.
Parent Route: (Where project can be set and updated)
onSubmit(value: any, valid: any) {
if (valid) {
// HTTP request to retrieve project
this.ad.searchProject(value)
.subscribe(
response => {
// If project found, set its value in the service
this.ad.setProject(response);
// Navigate to child route
this.router.navigate(['./project'], { relativeTo: this.route });
},
error => {
console.log(error)
},
() => {
console.log("Project Loaded");
}
);
}
}
Project service.ts
@Injectable()
export class ProjectService {
public project: Project;
// Observable string sources
private projectSource = new Subject<Project>();
// Observable string streams
projectListener$ = this.projectSource.asObservable();
constructor(private http: Http) {
}
searchProject(value: string): Observable<any> {
return this.http.post('/controller/Project/SearchProject', { value: value }, { headers: headers })
.map(response => response.json());
}
// Service message commands
setProject(project: Project) {
this.projectSource.next(project);
console.log("call setProject");
}
}
Child Route:
export class ChildComponent {
project: Project = null;
subscription: Subscription;
constructor(private ad: ProjectService) {
console.log("call child route");
this.subscription = this.ad.projectListener$.subscribe(
value => {
// Triggered after the second value entry
console.log("call subscription");
console.log(value);
this.project = value;
});
}
}
Console Log
[HMR] connected
call parent route
Gravity_Project
setProject
Project Loaded
call child route
// Completed first project entry
Waves Project
call subscription
Object {id: 1001, typeID: 45004, studentID: 10000…}
call setProject
Project Loaded
// Completed second project entry