2017-02-16 57 views
1

我有一个服务:Angular2服务的领域的问题

@Injectable() 
export class MyService implements IMyService { 
    myServiceArray: Array<string> = ["hi", "hello", "yoyo"]; 
} 

此项服务,更新字符串ngModel的阵列组件注入。当我尝试从组件或服务打印数组时,一切工作正常(也就是使用ngModel更新数组)。

我还@Inject在另一个1.

@Injectable() 
export class AnotherService implements IAnotherService { 

    constructor(public myService: MyService) { 
    } 

    printValues() { 
    console.log(this.myService.myServiceArray); 
    } 
} 

当我调用函数printValues()这样的服务,[ “喜”, “你好”, “YOYO”]即使印刷如果我更新的值带模型的阵列!

我在做什么错?

编辑:

组件的代码如下。

@Component({ 
    selector: 'app-root', 
    providers: [MyService], 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppCustomerData implements IAppCustomerData { 

    constructor(public myService: MyService) { 
    } 
} 
+2

你在哪里提供服务('@Component()'或'@NgModel()')? –

+0

我把组件的代码。 [(ngModel)] ='...'位于组件的templateUrl中。 – Nano

回答

2

你要看看你注入相同的服务来说,如果你有每一个有它自己的阵列服务的多个实例。

我会尝试使用本地存储将数据存储在服务上,比你可以有多个实例,每个人都可以编辑或返回相同的值: How to store token in Local or Session Storage in Angular 2?

也许这个回答您的问题: How do I create a singleton service in Angular 2?

+0

OMG你是对的!我实际上是创造更多的相同服务的实例。有没有办法做到单身? – Nano

+0

查看我添加到我的帖子中的链接。 – patrick

+0

谢谢,你写的正是我需要的! – Nano