观察到与异步管相结合的物体时,没有更新模板

问题描述 投票:0回答:1

我有打印的可观测值(测试$),以通过异步管的模板组件。

该组件属性需要基于组件的输入进行初始化,所以我赋予它的价值在ngOnInit可观察到的由服务(测试$)发出的。当服务被初始化由服务公开的可观察到的被分配给的受试者的组合。值并不在模板印刷。 Stackblitz

如果我定义合并臣下BehaviorSubject,模板被通知新的价值。

我想这已经是与冷/热观测。这是我的理解是,如果你订阅BehaviorSubject你总是会得到最新的值,即使你订阅之后发出的值,但与冷观测(如主题),你需要订阅的价值是为了发出通知之前, 。

那么,为什么是模板不倘认购事项发生的主体发出值之前更新?我的理由是,认购时发生模板被渲染,这是在ngOnInit。该科目不散发它们的值,直到这一步之后。

零件

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  @Input() initialValue: number;
  result$: Observable<number>;

  constructor(private service: TestService) {

  }

  ngOnInit() {
    console.log('component init');
this.result$ = this.service.result$;
// Get data based on inputs
this.service.initTransformedValue(this.initialValue);
  }


}

服务

@Injectable()
export class TestService {


  result$: Observable<number>;
  otherValue$: Observable<number>;
  transformedValue$: Observable<number>;

  constructor() {
    console.log('service constructor');
    this.init();
  }

  init(){
    this.result$ = combineLatest(
      this.transformedValue$,
      this.otherValue$
    ).pipe(map(([first, second]) => {
        console.log('have combined value');
        return first + second;
    })
    );
  }

  initTransformedValue(initialValue) {
    // Use timeout to simulate HTTP calls
    setTimeout(() => {
      console.log('service. emit transformedValue value');
      this.transformedValue$ = of(initialValue * 2);
    }, 1000);

setTimeout(() => {
      console.log('service. emit otherValue value');
      this.otherValue$ = of(initialValue * 4);
    }, 1200);



  }

}

模板

<p>{{result$ | async}}</p>
angular rxjs behaviorsubject subject
1个回答
0
投票

您正在创建一个新的观察到有,你需要使当前观察到发射一个新值。

https://stackblitz.com/edit/angular-fta9h1

你永远不应该重新分配观察到的另一个观察到的,你应该让现有的可观测EMIT,科目和行为主体可以通过拨打下一个发射。

const { of, BehaviorSubject } = rxjs;

let obs = of('of initial value');

obs.subscribe(val => { console.log(val); });

// This is a new observable and will not effect the subscription to a different obsevable
obs = of('of new value');

const bs = new BehaviorSubject('BehaviorSubject initial value');

bs.subscribe(val => { console.log(val); });

// This emits a new value on the same observable
bs.next('BehaviorSubject new value');
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.