After having done some research I was able to display the values in the template as such:
{{ this.array && this.array[0].lastName}} and this works but not sure how it works but it does work. Founded in a post somewhere.
{{ this.array && this.array[0].lastName}} , this works within the template but now i need to assign the array value to a variable to work with but simply doing testValue = this.array[0].lastName does not work.
I am using the new httpclient class to retrieve data not sure if that matters.
I’d really need to see some more code to help you with that… not necessarily the entire component, but the part where the array gets populated, where the testValue gets assigned etc. Or maybe you could provide a stackblitz mini-app with just the relevant code?
Thinking about it, that might indeed be the problem. Of course you can’t access elements of an array that is yet to be defined, hence the need for that array && array[0].lastName check (no need for the this though, that’s implicit within the template). Such a check utilises the short-circuit evaluation and is a common pattern in JS. Similarly, you can only assign elements of that array to another variable after the array got actually populated, i.e. from within the http subscription
I checked out stackblitz and its awesome, thanks. Nice little tool for sharing code with someone.
I created two files and basically copy/pasted the relevant code. My codes aren’t too complicated to start with still at the learning stage :
app/test.component.ts
app/test.service.ts
console.log(typeof returnArray); // received object
console.log(typeof returnArray[0]); // received object
console.log(typeof returnArray[0].lastName); // received undefined
Isn’t it. :-) Anyway, the problem is that you’re doing the assignment right in the ngOnInit() method while the HTTP request is still pending:
ngOnInit(){
this.getUserInformationMethod(this.testValue);
// this will never be true
if (this.returnArray){
this.userName = this.returnArray[0].lastName;
}
}
Remember, the first A in AJAX stands for “asynchronous”… so you’ll have to do this assignment in the success callback of the service: