Angular 2 - Implementation of shared services

喜你入骨 提交于 2019-11-30 18:58:10

问题


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.


回答1:


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                    
                  );
     }
}


来源:https://stackoverflow.com/questions/35993778/angular-2-implementation-of-shared-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!