Answer the question
In order to leave comments, you need to log in
How to loop through an array of an object?
Good afternoon!
The component has a Blog
object
. In the html output:
<div *ngFor="let oneBlog of Blog.Blog">
<p>Опубликовано - {{oneBlog.Release}}</p>
</div>
<div>
<p>Опубликовано - {{Blog.Blog[0].Release}}</p>
</div>
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/pages/post/post.component.html:8:27 caused by: undefined is not an object (evaluating 'self.context.Blog.Blog')
import { Component, OnInit} from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { Response} from '@angular/http';
import { HttpService} from '../../services/http.service';
@Component({
moduleId: module.id,
selector: 'post-app',
templateUrl: 'post.component.html',
providers: [HttpService]
})
export class PostComponent implements OnInit {
Blog = [];
id;
constructor(private activateRoute: ActivatedRoute,private httpService: HttpService){
this.id = activateRoute.snapshot.params['id'];
}
ngOnInit(){
this.httpService.getOnePost(this.id).subscribe((data: Response) => this.Blog=data.json());
}
}
<button (click)="testMe()">Test</button>
testMe(){
console.log(this.Blog.Blog.Release);
}
Answer the question
In order to leave comments, you need to log in
I would leave the template as it is (with Array), and in the controller I would do this:
In general, if there is access to the backend, then I would redo it so that the method instead of Blog returns Blogs when there are a lot of them
A little more data is needed. Blog is just an object or a Promise? What is Blog.Blog? When and how is this property initialized?
If you try like this?
<div *ngFor="let oneBlog of Blog.Blog">
<p *ngIf="Blog.Blog?.length > 0">Опубликовано - {{oneBlog.Release}}</p>
</div>
You have different types... In the first case Blog is Array and in the second case Object, you can see in the screenshots
Published - {{Blog.Blog[0].Release}}
Should be replaced with
Published - {{Blog.Blog.Release}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question