如何在管道异步和组件中使用对象?

发布于 2025-02-13 16:27:21 字数 163 浏览 1 评论 0原文

我需要两次使用可观察的参考。 在HTML中:

<div *ngIf="subject$ | async as subject">

在模板中:

this.subject = subject

I need to use the reference of observable twice.
in html:

<div *ngIf="subject$ | async as subject">

and in template:

this.subject = subject

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

假装爱人 2025-02-20 16:27:21

您可以使用 .pipe> .pipe() 将数据, 然后使用 tap() 将值提取到组件中存在的变量中。

@Component({
  template: `
    <div *ngIf="subject$ | async as subject">
      <!-- do something with "subject" -->
      <span>{{subject.someProp}}</span>
    </div>
  `
})
export class MyComponent {
  // Used within the typescript
  subject = '';

  // Used within the html
  // Assuming data is retrieved through some sort of service
  subject$ = this.service.getData().pipe(
    tap(i => this.subject = i)
  )
}

You can use a .pipe() to pipe the data, then use tap() to extract the value into a variable that exists within the component.

@Component({
  template: `
    <div *ngIf="subject$ | async as subject">
      <!-- do something with "subject" -->
      <span>{{subject.someProp}}</span>
    </div>
  `
})
export class MyComponent {
  // Used within the typescript
  subject = '';

  // Used within the html
  // Assuming data is retrieved through some sort of service
  subject$ = this.service.getData().pipe(
    tap(i => this.subject = i)
  )
}
肩上的翅膀 2025-02-20 16:27:21

如果您想获得代码中的值,

this.subject$.subscribe((value) => this.subject = value);

我想您需要订阅,这是您的进程;但是,Alias 作为主题仅在标签内部存在。

您应该使用 share() >确保您不会触发两次的东西(例如服务器请求):

private subject$ = new Subject<any>();
public observable$ = this.subject$.map(share());

其他好处是可观察现在是可观察到的无法在“消耗代码”上发出新值。

If you want to get the value in you code, you need to subscribe

this.subject$.subscribe((value) => this.subject = value);

I guess, that this was your intenion; but the alias as subject only exists inside the tag it was defined.

You should use the share()Operator to ensure you do not trigger something twice (like a server request):

private subject$ = new Subject<any>();
public observable$ = this.subject$.map(share());

additional benefit is that observable is now an Observable which can not be used to emit a new value at the "consuming code".

烟雨凡馨 2025-02-20 16:27:21

希望该解决方案可以帮助您了解如何使用可观察的两次 https://stackblitz.com/edit/angular-ivy-jgcgnf?file=src/app/app/app/app.component.ts

Hopefully, this solution can help you to understand how to use observable twice https://stackblitz.com/edit/angular-ivy-jgcgnf?file=src/app/app.component.ts

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文