异步管道到src图像属性-Angular 2+ [英] async pipe into src image attribute - Angular 2+

查看:99
本文介绍了异步管道到src图像属性-Angular 2+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在可观察和异步管道方面遇到问题.我在组件中输入了Observable.在控制器中以及在ngOnInit中可观察的订阅中,im获得有效值.问题出在模板上,我在模板上没有得到有效的值.我想在图像src属性中具有异步功能.

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(可观察到返回)

TvShowComponent (return Observable)

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

TvShowComponent模板(使用嵌套组件)

TvShowComponent template (using nested component)

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

CoverThumbnailComponent(带有Input()) @Input()public coverLink $:可观察;

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

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

CoverThumbnailComponent模板(但不适用于:()

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>

推荐答案

问题是此行:

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

您正在传递一种返回Observable<string>的方法,该方法在Angular中不起作用.

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

您需要制作一个Observable<string>并将其分配给它.例

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

coverLink$: Observable<string>;

然后在ngOnInit上或您要调用该方法的任何地方.

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

this.coverLink$ = this.getCoverLink();

您的html然后变为<fp-cover-thumbnail [coverLink$]="coverLink$"></fp-cover-thumbnail>

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

或者,您无需将Observable传递给子组件,只需执行<fp-cover-thumbnail [coverLink]="coverLink$ | async"></fp-cover-thumbnail>即可,其中子组件上的Input()现在可以只是一个字符串.

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.

这篇关于异步管道到src图像属性-Angular 2+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆