Reputation: 6796
I'm trying to implement a solution I found right here in Stack Overflow, but facing difficulty. I've a service and a component and something is not correct on the implementation.
The error: TypeError: Cannot read property 'next' of undefined What could be wrong or missing ? Is there something more missing ? Also on my terminal window, I got this error, but it's not reflect on my browser console: error TS1005: '=>' expected.
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
@Injectable()
export class GlobalService {
data: any;
dataChange: Observable<any>;
constructor() {
this.dataChange = new Observable((observer:Observer) { // this is the TS1005 error.
this.dataChangeObserver = observer;
});
}
setData(data:any) {
this.data = data;
this.dataChangeObserver.next(this.data); //Line of the critical error (next)
}
}
and this is the component that's consume the service....(I will place only the relevant lines)
import {GlobalService} from "../../../global.service";
import(...)
@Component({
providers: [GlobalService],
template: `<p>{{myData}}<>/p><span (click)="addTag(1, 'test')">Add more</span>`
});
export class MyComponent {
addTag (id,desc){
this._global.setData({ attr: 'some value' });
}
}
constructor(private _global: GlobalService) {
}
So, what's wrong and/or missing to make this simple component display results and add new elements and be observable ? I never implemented observables before.
Upvotes: 3
Views: 8984
Reputation: 55443
Your code is not so clear and so becomes hard to understand. Still tried to help you this way. Check and let me know if it doesn't work.
...
import {Injectable,EventEmitter,Output} from 'angular2/core';
@Injectable()
export class GlobalService {
data: any;
@Output dataChangeObserver: EventEmitter=new EventEmitter();
constructor() {
});
setData(data:any) {
this.data = data;
this.dataChangeObserver.emit(this.data);
return this.dataChangeObserver;
}
}
export class MyComponent {
constructor(private _global: GlobalService) {
}
addTag (id,desc){
this._global.setData({ attr: 'some value' })
.subscribe((res)=>{this.myData=res},
err=>console.log(err), //removed dot
()=>console.log('recived data') //removed dot
);
}
}
Upvotes: 7