angular - 如何防止组件更新服务

标签 angular angular2-services

我是 Angular 4 的新手,正在尝试设置一个服务,该服务包含一些数据,这些数据不应该由它提供数据的任何组件进行编辑。例如,这是我的服务的简化版本:

@Component({
  providers: [ArgumentService]
})

@Injectable()
export class ArgumentService {
  pronouns: Object[];
  constructor() {

   this.pronouns = [{'type': "1SG", 'value': 'n', "series": "I"},
                    {'type': "2SG", 'value': 'm', "series": "I"},
                    {'type': "1SG", 'value': "'y", "series": "II"},
                    {'type': "2SG", 'value': 'n', "series": "II"},
                    {'type': "1SG", 'value': "'nii'y", "series": "III"},
                    {'type': "2SG", 'value': "'niin", "series": "III"}];

  }

  getPronouns(){
    return this.pronouns
  }

}

对象数组不应更改。但是,下面组件中的示例函数更改了数组中的第一个对象:

import { Sentence } from '../sentence.model'
import { VerbService, ArgumentService } from '../../services/'
import { RadioButtonComponent } from '../radio-button/radio-button.component'


@Component({
  selector: 'app-sentence',
  templateUrl: './sentence.component.html',
  styleUrls: ['../../bootstrap.min.css', './sentence.component.scss', '../app.component.scss'],
  providers: [VerbService, ArgumentService]
})

export class SentenceComponent implements OnInit {

  constructor(public verbService: VerbService, public argumentService: ArgumentService) {

    this.example()

  }


  example(){
    let arg = this.argumentService.getPronouns()[0]
    arg['position'] = 'S'
    console.log(this.argumentService.getPronouns()) // this gives {'type': "1SG", 'value': 'n', "series": "I", "position": "S"} when it should give {'type': "1SG", 'value': 'n', "series": "I"}
  }

  ngOnInit() {
  }

}

也许我认为这种数据应该放在服务中是错误的?服务是否总是应该从其组件进行更新?我非常感谢对此的任何建议或指导。

提前致谢。

最佳答案

getPronouns(){
    return this.pronouns.map(p => Object.assign({}, p))
}

这不仅会返回数组的副本,还会返回其所有内容的副本。 (我之前的尝试,this.pronouns.slice(),复制数组,但用对相同对象的引用填充它)

关于angular - 如何防止组件更新服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584848/

相关文章:

angular - 自定义 Ag-Grid 主题的问题

javascript - Angular 2 : select not updating with selected value in ion-select Ionic 2?

javascript - 将 int 插入 String 数组

Angular - 如何正确使用 Services、HttpClient 和 Observables 在我的应用程序中传递对象数组

c# - Angular 5 和 .NET Core 2.1 API : Getting current time in user's timezone

rest - 使用一个 REST 调用的 Angular2 多个组件

angular - subscribe 不是尝试在 Angular 2 中使用 JSON 文件时抛出的函数错误

javascript - 在数据有机会加载之前的 Ionic 2 View 渲染(和错误)

angular - Http.Get() 总是在 Angular 2 中返回未定义

angular - 如何在 Angular 2 中重新加载相同 URL 的组件?