Angular 角度5.-组件属性未更新???为什么?
我有一个ProgressLoader组件:Angular 角度5.-组件属性未更新???为什么?,angular,service,components,Angular,Service,Components,我有一个ProgressLoader组件: import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { ProgressLoaderService } from './progress-loader.service'; @Component({ selector: 'app-progress-loader', template
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ProgressLoaderService } from './progress-loader.service';
@Component({
selector: 'app-progress-loader',
templateUrl: './progress-loader.component.html',
styleUrls: ['./progress-loader.component.scss']
})
export class ProgressLoaderComponent implements OnInit {
public prgLoaderSubscription: Subscription;
// Loader Type
public prgLoaderType;
constructor(private _pl: ProgressLoaderService) {
this.prgLoaderType = 'spinner';
}
ngOnInit() {
this.prgLoaderSubscription = this._pl.loaderSubject$.subscribe(data => {
this.prgLoaderType = data.loaderType;
console.log('**************************', this.prgLoaderType);
});
}
}
和progressLoaderSerice:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ProgressLoaderService {
private loaderSubject = new Subject<any>();
public loaderSubject$ = this.loaderSubject.asObservable();
constructor() { }
setLoaderType(loaderType) {
this.loaderSubject.next({loaderType: loaderType});
}
}
从'@angular/core'导入{Injectable};
从'rxjs/Subject'导入{Subject};
从“rxjs/Observable”导入{Observable};
@可注射()
导出类ProgressLoaderService{
私有loaderSubject=新主题();
public loaderSubject$=this.loaderSubject.asObservable();
构造函数(){}
setLoaderType(loaderType){
this.loaderSubject.next({loaderType:loaderType});
}
}
从另一个组件调用setLoaderType()
如下:
这个._pl.setLoaderType('WTF!!!')
现在progressLoaderComponents onInit()订阅中的console.log()会输出
WTF代码>但是无论我尝试什么,属性prgLoaderType
都没有更新。。这怎么可能呢?基于您共享的代码,我在stackblitz上创建了一个angular项目
看一看
我看不出你的代码有什么问题。它应该按原样工作,我没有修改它。查看app.module.ts
以查看导入是否正确。同样在app.component.ts
中,我每1秒调用一次您的服务,持续10秒,正如您所看到的,您的组件中的变量每次都在被设置。您能为此添加一个stackblitz吗?谁调用setLoaderType()
函数?@Luca。。另一个组件你也可以发布吗?