角2 - 共享服务的实施 [英] Angular 2 - Implementation of shared services

查看:400
本文介绍了角2 - 共享服务的实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个解决方案,我发现这里在堆栈溢出,但面临的困难。我有一个服务,一个组成部分,东西是不是在正确的执行。

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.

错误:类型错误:无法读取属性未定义的下一步
可能是什么错误或丢失?是不是有什么人失踪?
也是我的终端窗口上,我得到这个错误,但它不是我的浏览器控制台上反映:错误TS1005:'=>'有望

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.

推荐答案

您code还不是很清楚,因此变得很难理解。还是尽力帮你这个样子。检查,让我知道,如果它不能正常工作。结果

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

这篇关于角2 - 共享服务的实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆