Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a component.
In the app component, there is a checkbox that allows users to select a category of books. When a new item is checked, the ChangeMessage method is called to send the Categoryid ID. This method then updates the list of books and shares it with another component for display:
@Injectable({providedIn:'root'})
export class DataService {
private Messagesource = new Subject<any>();
curentMessage$ = this.Messagesource.asObservable()
constructor(private http: HttpClient, @Inject('BASE_URL') public url: string) { }
ChangeMessage(message: any) {
let result = this.http.get<Book[]>(this.url + 'api/Books');
this.Messagesource.next(result);
}
}
In the other component, the list of books is retrieved and updated as follows:
export class BookComponent implements OnInit {
booklist: Book[]
constructor(public service:CategoryServic,private ds:DataService) {}
ngOnInit(): void {
this.ds.curentMessage$.subscribe(x => this.booklist = x)
}
}