I have a component like this using an apiService, where I follow this approach using BehaviourSubject to share data from my API:
Angular 4: How to pass API data from one component into another component?
settings.component.ts :
export class SettingsComponent implements OnInit {
data: Observable<Setting[]>;
public selectedSetting: Setting;
constructor(private apiService: ApiService,
private router: Router) { }
// Load Setting while starting
ngOnInit() {
// this.getSettings();
this.data = this.apiService.fetchData();
}
onSelect(setting: Setting): void {
this.selectedSetting = setting;
}
clearSelect(): void {
this.selectedSetting = null;
}
goToSettingDetail(): void {
this.router.navigate(['settingsDetail']);
}
}
api.service.ts:
export class ApiService {
private API_URL = 'someUrl';
public subject$: BehaviorSubject<Setting[]> = new BehaviorSubject<Setting[]>([]);
constructor(private httpClient: HttpClient) {
}
// use async pipe in html template "*ngFor= let s of settings | async"
// and just inject ApiService in components constructor
fetchData() {
const fetch$: Observable <Setting[]> = this.getSettings().pipe(share());
fetch$.pipe(
map(allSettings => this.subject$.next(allSettings))
)
.subscribe();
return fetch$;
}
/** GET settings from API*/
getSettings(): Observable<Setting[]> {
return this.httpClient.get<Setting[]>(this.API_URL + '/settings')
.pipe(
catchError(this.handleError('getSettings', []))
);
}
}
So if I have a part in a html file like this:
<table>
<tr>
<th align="left">Id</th>
</tr>
<tr *ngFor="let s of data | async">
<td>{{s.Id}}</td>
<td>
<button (click)="onSelect(s); goToSettingsDetail()">ViewSettings</button>
</td>
</tr>
</table>
What is the correct way with still using BehaviourSubject for getting selected Object in other components? If I use an additional service, which fetchs the selected object from settingsComponent it isn't related with BehaviourSubject anymore right? So if I do changes on selected object in other component, no one will notice.
Can you give me some hints? :)
setSelectedSetting(s: Setting) { this.apiService.setSelectedSetting(s)}
Now in subcomponent.ts:
1. Inject apiService
2. selectedSetting: Observable