I am trying to execute several receive requests using Angular2 in Django / python.
I can execute an API request and get a list of users to find the current user id. Then I perform an operation .flatMapto execute a second query to get a list of all comments. I compare userId with a list of comments to select only the comments made by the user. All the data I get is JSON.
At this point, I am trying to get an article that belongs to each comment made. But when I try to run a function to try to get data in a for loop, the request is not even executed.
Here is my service:
import {Injectable} from "angular2/core";
import {Http, Headers, Response} from "angular2/http";
import 'rxjs/Rx';
import {Observable} from "rxjs/Observable";
@Injectable()
export class DataService {
profileUserName: profileUserName = document.getElementsByClassName('profile-user-name')[0].children[0].innerHTML;
userComments: [];
constructor (private _http: Http) {}
getUsers(): Observable<any> {
return this._http.get('/api/v1/users/?format=json')
.map((res: Response) => {
this.userList = res.json();
// select only comments made by current user
for (i = 0; i < this.userList.length; i++) {
if(this.profileUserName == this.userList[i].username){
this.userId = this.userList[i].url
}
}
})
.flatMap(() => this._http.get('/api/v1/article_comments/?format=json')).map((res: Response) => {
this.commentList = res.json();
let userComments = [];
for (i = 0; i < this.commentList.length; i++) {
if (this.commentList[i].user == this.userId) {
userComments.push(this.commentList[i])
}
}
this.userComments = userComments;
return this.parseArticleComments();
})
}
parseArticleComments() {
for (i = 0; i < this.userComments.length; i++) {
this.currentSelection = this.userComments[i];
this.getArticleComments(this.currentSelection)
}
// response should/is returned here to the appComponent
return this.userComments
}
// currently not performing any http requests
getArticleComments(currentSelection): Observable<any> {
// currentselection.article == http://localhost:8000/api/v1/articles/10/?format=json
return this._http.get('currentselection.article')
.map((res: Response) => {
console.log('entered');
currentSelection.articles = res.json();
return currentSelection.articles;
})
}
}
Here is my app.component:
import {Component, OnInit} from 'angular2/core';
import {DataService} from './data.service.ts';
@Component({
selector: 'http-app',
template: `
<div>
<button (click)="logGetRequest()">Log Reqeust</button>
<ul>
<li *ngFor="let comment of commentList"> {{ comment.article }} </li>
</ul>
</div>
`,
providers: [DataService]
})
export class AppComponent{
commentList: string;
constructor ( private _dataService: DataService) {}
//get list of users to find user ID
getUserList = this._dataService.getUsers()
.subscribe(
data => this.commentList = (data),
error => console.error(error)
);
logGetRequest() {
console.log(this.commentList);
}
}
, ?