async pipe into src image attribute - Angular 2+

假装没事ソ 提交于 2019-12-25 03:17:57

问题


i have problem with observable and async pipe. I have input in my component with Observable. In controller and on subscribe into observable in ngOnInit im get valid values. Problem is in template, I do not get valid values on template. I want to have async in image src attribute.

TvShowComponent (return Observable)

    public getCoverLink(): Observable<string> {
      return this.tvShowForm.get('cover').valueChanges.pipe(map((coverLink:  string) => {
        return coverLink;
      }));
  }

TvShowComponent template (using nested component)

<fp-cover-thumbnail [coverLink$]="getCoverLink()"></fp-cover-thumbnail>

CoverThumbnailComponent (with Input()) @Input() public coverLink$: Observable;

ngOnInit() {
    this.coverLink$.subscribe(data => {
        console.log(data); // works here
    });
}

CoverThumbnailComponent template (but not works here :( )

<div class="cover-thumbnail-container">
<img #cover [src]="(coverLink$ | async)"> <!-- here not work -->
coverLink: {{ (coverLink$ | async) }} <!-- also here not work -->
</div>

回答1:


The issue is this line:

<fp-cover-thumbnail [coverLink$]="getCoverLink()"></fp-cover-thumbnail>

You are passing a method that returns Observable<string> well, that doesn't work in Angular.

You need to make a Observable<string> and assign it to that. Ex.

coverLink$: Observable<string>;

Then on ngOnInit or whereever you want to call the method.

this.coverLink$ = this.getCoverLink();

Your html then becomes <fp-cover-thumbnail [coverLink$]="coverLink$"></fp-cover-thumbnail>

Alternatively you don't need to pass in an Observable to your child component you can just do <fp-cover-thumbnail [coverLink]="coverLink$ | async"></fp-cover-thumbnail>, where your Input() on your child component can be just a string now.



来源:https://stackoverflow.com/questions/52611332/async-pipe-into-src-image-attribute-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!