当变量在订阅中发生变化时,为什么视图没有更新?
我有这个代码:
example.component.ts
testVariable: string;
ngOnInit() {
this.testVariable = 'foo';
this.someService.someObservable.subscribe(
() => console.log('success'),
(error) => console.log('error', error),
() => {
this.testVariable += '-bar';
console.log('completed', this.testVariable);
// prints: foo-Hello-bar
}
);
this.testVariable += '-Hello';
}
Run Code Online (Sandbox Code Playgroud)
example.component.html
{{testVariable}}
Run Code Online (Sandbox Code Playgroud)
但视图显示:foo-Hello.
为什么不显示:foo-Hello-bar?
如果我ChangeDetectorRef.detectChanges()
在订阅中调用它将显示正确的值,但为什么我必须这样做?
我不应该从每个订阅中调用此方法,或者根本不应该(angular应该处理这个).有正确的方法吗?
我是否遗漏了Angular/rxjs 5到6的更新内容?
现在我有Angular版本6.0.2和rxjs 6.0.0.相同的代码在Angular 5.2和rxjs 5.5.10中正常工作,无需调用detectChanges
.
问题:是否存在定义单页应用程序路由的最佳实践?
在Angular项目中,功能通常在延迟加载的模块中分开,然后在路由AppRoutingModule
和延迟加载的模块中配置路由。
假设该应用将管理目录,例如:产品。路由可以这样配置:
选项1:
/products
/products/create
/products/:id
/products/:id/edit
它可以工作,但看起来有点混乱,并且和之间有些歧义/products/:id
,/products/create
因为参数:id
可以匹配字符串“ create”。示例代码:
app-routing.module.ts:
const routes: Routes = [
{
path: '',
children: [
{ path: 'products', loadChildren: 'app/products/products.module#ProductsModule' },
]
}
];
Run Code Online (Sandbox Code Playgroud)
products-routing.module.ts
const routes: Routes = [
{ path: '', component: ListProductsComponent },
{ path: 'create', component: CreateProductComponent },
{ path: ':id', component: ViewProductComponent },
{ path: ':id/edit', component: EditProductComponent },
];
Run Code Online (Sandbox Code Playgroud)
选项2
/products
/products/create
angular ×1
angular-cli ×1
angular6 ×1
lazy-loading ×1
observable ×1
routes ×1
rxjs6 ×1
subscribe ×1