I have a function that returns an Observable<Person[]>
, where Person is my model:
export interface Person {
id: string;
age: number;
}
Now in my component.ts, I am calling this function and aiming to retrieve the array to display it in the HTML.
An example of the array that is returned looks like this:
[{"id":"13434 1","age":21},{"id":"34334 1","age":27}]
I have two buttons that trigger the same function.
In my component.ts, I have three methods that are triggered when these buttons are clicked. I want to set a variable to store the returned value of the Observable within these methods. However, my attempts have been unsuccessful...
These are the functions:
@Injectable()
export class MyCmp implements OnInit {
listOneData: Observable<Person[]>;
listTwoData: Observable<Animal[]>;
showListOne = false;
showListTwo = false;
constructor(private _myService: MyService) {
};
public showListOneData(): void {
this.showListOne = true;
this.showListTwo = false;
this._myService.getListOneData().subscribe(res => {
this.listOneData = res;
})
}
public showListTwo(): void {
this.showListTwo = true;
this.showListOne = false;
this._myService.getListTwoData().subscribe(res => {
this.listTwoData = res;
})
}
}
this.listTwoData = res;
- This line does not compile because I am assigning Person[]
to
listOneData: Observable<Person[]>;
. However, even if I remove the Observable<>, it still does not work.
Can someone please provide an efficient way to achieve this? I do not want to handle it asynchronously as I intend to send an array to the HTML. Also, where should I handle the unsubscribe action in the code?
Thank you very much!