I am new to Angular 4 and am trying to set up a service that has some data that should not be able to be edited by any of the components it provides data to. For example, here is a simplified version of my service:
@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
}
}
The array of objects should not change. However, the example function in the component below changes the first object in the array:
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() {
}
}
Maybe I am wrong in thinking that this kind of data should go in a service? Are services always supposed to update from their components? I would really appreciate any advice or guidance on this.
Thanks in advance.
getPronouns(){
return this.pronouns.map(p => Object.assign({}, p))
}
This will return not just a copy of the array but a copy of all its contents. (My previous attempt, this.pronouns.slice(), copies the array but fills it with references to the same objects)