【发布时间】:2021-06-22 02:27:07
【问题描述】:
在下面的代码中,我试图显示从 observables 返回的值。返回值的可观察函数是 在服务中创建如下代码所示。
在 manin 组件中,如下所示,我从服务对象访问该方法并将假定的返回值分配给 一个变量。该变量通过插值链接到模板,如下面的模板部分所示。
我面临的问题是,当我运行代码时,值不会从服务传递到组件,因此 模板没有变化
请告诉我如何更正代码,以便使用服务中可观察对象的正确值更新模板
组件: 值:无效;
constructor(private myservice: MyService1Service) {}
ngOnInit(){
this.todaydate2 = this.myservice.showTodayDate();
this.value = this.myservice.observablesTest();
}
服务:
import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Observable, Observer } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyService1Service {
name : string;
obsValue: Observable<unknown>;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.name = params['name'];
});
}
showTodayDate() {
let ndate = new Date();
return ndate;
}
observablesTest() {
this.obsValue = new Observable((observer) => {
console.log("Observable starts")
setTimeout(() => { observer.next("3000") }, 1000);
});
}
}
.html
<b>todayDate is: {{todaydate2}}</b>
<b>observableValue is: {{value}}</b>
注意:
我试过了
{{ value | async }}
但 html 模板中仍然没有显示任何内容
【问题讨论】:
-
写
{{ value | async }}怎么办 -
@Emilien 仍然没有显示任何内容
标签: javascript node.js angularjs angular observable