我正在尝试将变量从我的服务更新到组件。当我尝试在组件中订阅它时,我收到错误。谁能帮助我。
import {Injectable, } from 'angular2/core';
import {Router} from 'angular2/router';
import {MasterComponent} from '././master/master.component';
import 'rxjs/Rx';
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription"
import {Subject} from "rxjs/Subject"
@Injectable()
export class ConnectService
{
showValues: string;
public showValuesChange: Subject<string> = new Subject<string>();
constructor() {
this.showValues="1";
}
recvNotify(m) {
buttonName = innervalue;
console.log("ELSEinnervalue",buttonName);
switch (buttonName) {
case "0x01010000":
console.log('showValue==1');
this.showValues = "1";
this.showValuesChange.next(this.showValues);
break;
case "0x01020000":
console.log('showValue==2');
this.showValues = "2";
this.showValuesChange.next(this.showValues);
$('#showValue').prop("value",2);
break;
default:
console.log('showValue==3');
this.showValues = "3";
this.showValuesChange.next(this.showValues);
break;
}
}
}
组件:这里我希望在值发生变化时从服务中获取更新的showValues。
import {Component} from 'angular2/core';
import {ConnectService} from '../connect.service';
import {Router} from 'angular2/router';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
@Component({
selector: 'Master',
templateUrl: './app/master/master.component.html',
providers: [ConnectService]
})
export class MasterComponent {
//showValue: any;
public showValues: string;
//show: any;
constructor(
public connectService: ConnectService,
public _router: Router,
public _subscription: Subscription){
if(localStorage.getItem("clientStatus")=='connected'){
this.showValues = connectService.showValues;
this._subscription = connectService.showValuesChange.subscribe((value) => {
this.showValues=value;
console.log("import {Observable} from 'rxjs/Observable';",this.showValues);
});
this._router.navigate(['Master']);
} else {
this._router.navigate(['Home']);
}
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}