Reputation: 121
I am trying to use switchMap operator. But it should call different http requests based upon the params. So for different http requests the data from subscribe will also be deifferent. How to properly handle that data. Right now i am getting typescript error..My code..
ngOnInit(){
this.route.params.pipe(switchMap(params => {
if (params === 'friends') {
return this.http.get('some url to get friendList')
} else if (params === 'chats') {
return this.http.get('some url to get chats')
}
})).subscribe((result: {message: string, friendList: []} | {message: string, chats: []}) => {
console.log(result)
})
}
Here basically i am getting different structured data for calling two different api based upon condition. So i am trying to work with the result which i am getting from subscribe like..
.subscribe((result: {message: string, friendList: []} | {message: string, chats: []}) => {
if(result.friendList) {
// do something
} else if (result.chats) {
//do something
}
})
Here i am getting typescript errors on using like result.friendList
or result.chats
. So how should i work with the result?
Upvotes: 0
Views: 35
Reputation: 344
You can change the type of the result to any and then the conditions will work properly and the typescript will pass without errors.
.subscribe((result: any) => {
if(result.friendList) {
// do something
} else if (result.chats) {
//do something
}
})
if you want to specify the type you can make it with that:
{message: string, friendList: [] , chats: []}
and when one of the arrays is empty you can check the lengths and reach the condition
Upvotes: 1