简体   繁体   中英

how to use object in pipe async and in component?

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

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

and in template:

this.subject = subject

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)
  )
}

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM