【问题标题】:Angular2 Service's field issueAngular2服务的现场问题
【发布时间】:2017-07-05 10:45:16
【问题描述】:

我有一个服务:

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

这个服务被注入到一个用 ngModel 更新字符串数组的组件中。当我尝试从组件或服务打印数组时,一切正常(又名数组使用 ngModel 更新)。

我也在另一个 1 中 @Inject 这样的服务。

@Injectable()
export class AnotherService implements IAnotherService {

  constructor(public myService: MyService) {
  }

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

当我调用 printValues() 时,即使我使用模型更新了数组的值,也会打印 ["hi", "hello", "yoyo"]!

我做错了什么?

编辑:

组件的代码如下。

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

export class AppCustomerData implements IAppCustomerData {

  constructor(public myService: MyService) {
  }
}

【问题讨论】:

  • 你们在哪里提供服务(@Component()@NgModel())?
  • 我放了组件的代码。 [(ngModel)]='...' 在组件的 templateUrl 中。

标签: javascript angular typescript angularjs-scope


【解决方案1】:

如果你有多个服务实例,每个实例都有自己的数组,你必须看看你注入的是同一个服务实例。

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

也许这可以解决您的问题: How do I create a singleton service in Angular 2?

【讨论】:

  • 天哪,你是对的!我实际上正在创建相同服务的更多实例。有没有办法让是单例?
  • 查看我添加到帖子中的链接。
  • 谢谢,你写的正是我需要的!
猜你喜欢
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2013-05-20
  • 1970-01-01
相关资源
最近更新 更多