I have a search bar in
app.component.tsthat has an input value.results.component.tsis embedded with a router-outlet inapp.component.htmlWhen
results.component.tsis the current activated route, the search works fine and so do the results.However, if someone clicks on a result,
results.component.tsis replaced with a different component viewdetail.component.ts(it provides them with more information about the result.)On
detail.component.tsI have a "back to results" link setup with arouterLink='/'. And mind you, the search query is still present in the search bar because that view never gets replaced.When this back button is clicked,
results.component.tsreloads and firesngOnInit.
The problem: I can't access the value of the search string in app.component.ts from results.component.ts ngOnInit to repopulate the results. I've tried almost everything I can think of.
I already have a service built, but I don't know how to set it up to communicate that value, if that is the solution.
Updated with code
app.component.html
//other html
<input placeholder="What do you want to learn?" name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchCourse($event)">
interaction-service.service.ts:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class InteractionService {
// Observable string sources
private searchStr = new Subject<string>();
// Observable string streams
searchStr$ = this.searchStr.asObservable();
sendString(searchString: string) {
this.searchStr.next(searchString);
}
}
app.component.ts:
//other imports
import {InteractionService} from './interaction-service.service';
@Component({
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [CourseService, InteractionService]
})
export class AppComponent implements OnInit {
searchStr: string;
constructor(private _courseService: CourseService, private _interactionService: InteractionService, private router: Router) {
}
ngOnInit() {
}
searchCourse(event) {
this._interactionService.sendString(event.target.value);
this.router.navigateByUrl('/');
}
}
course-listings.component.ts (I referred to this as results above)
// other imports
import {Subscription} from 'rxjs';
import {InteractionService} from '../interaction-service.service';
@Component({
selector: 'app-course-listings',
templateUrl: './course-listings.component.html',
providers: [CourseService],
})
export class CourseListingsComponent implements OnInit {
//some other properties defined
@Input() searchStr: string;
subscription: Subscription;
constructor(private _courseService: CourseService, private _interactionService: InteractionService) {
this.subscription = this._interactionService.searchStr$.subscribe(
courses => {
this.searchStr = courses;
// code for returning results here..
}
);
}
ngOnInit() {
}
}