This question already has answers here:
Angular 2 - Displaying async Object data from promise (7 answers)
Closed 5 months ago.
I need to use async pipe without ngFor. I need to check property of object that is async loaded with observable.
This is what i want, but not working:
<ion-item *ngIf="user$.anonymouse | async">
<ion-label>Login</ion-label>
</ion-item>
//EDIT: I getting this error when i use code above
EXCEPTION: Invalid argument 'true' for pipe 'AsyncPipe' in [!user$.anonymouse | async in SettingsPage@27:22]
Is there any way how to solve this?
I know i can subscribe to this observable in Ctrl a store values into normal variable but i dont want to do that, because of perfomance etc.
4条答案
按热度按时间chy5wohz1#
The error is surprisingly accurate as the
*ngIf
directive expectstrue
orfalse
and uses the resulting expression to determine whether or not to render theHTML
element in the DOM.EXCEPTION: Invalid argument 'true' for pipe 'AsyncPipe' in [!user$.anonymouse | async in SettingsPage@27:22]
The expression you have is
user$.anonymouse
which evaluates as truthy, but unfortunately you cannot use theasync
pipe with this directive. Theasync
pipe "transforms" (also known as "pipes") the input exposing the resulting output within the scope of the*ngFor
directive for example.The pipe expects one of three possible types, defined below ( detailed about AsyncPipe ):
transform(obj: Observable<any>| Promise<any>| EventEmitter<any>)
Is there any way how to solve this?
Yes, you can either use it as it was designed. For example in an
*ngFor
directive:Or you could remove the piping altogether as it's not needed for the
*ngIf
directive:9lowa7mx2#
As stated in the comments by @Sean, your
*ngIf
statement should be based on the resulted object propertyanonymouse
of theuser$
object that is returned. As such:This worked for me and here is an example of how to use the results from the pipe below:
Component
View
A working example can be found here .
ki1q1bka3#
请注意,我从
user$
切换到了user
,如果愿意,您可以使用相同的变量名,但这更清楚地表明该值不再是异步管道。im9ewurl4#
如果你的用户是匿名的,那么你就可以使用这个方法。