更新找到解决方案
我想从instagram api获取所有页面(https://api.instagram.com/v1/tags/ {tag-name} / media / recent?access_token = ACCESS-TOKEN) 在它的回应中,有' next_url'参数,使用它可以获得新页面。 我尝试了递归,但它在~13步时杀了浏览器; 成分:
import { Component, OnInit } from '@angular/core';
import {InstagramService} from './instagram.service';
import {Search} from '../search';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
posts: Post[];
tag: String = 'blabla23';
constructor(
private instagramService: InstagramService
) {}
ngOnInit() {
this.getPosts();
this.posts = [];
}
getPosts(nextUrl?: string): void {
this.instagramService
.getTagMedia(this.tag, nextUrl)
.then((result: Search) => {
this.posts = this.posts.concat(this.posts, result.getMedia());
if (result.getNextUrl() != null) {
this.getPosts(result.getNextUrl().toString());
}
});
}
}
服务:
import { Injectable } from '@angular/core';
import { Jsonp, Response, Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/delay';
import { Search } from './search';
@Injectable()
export class InstagramService {
private apiUrl = 'https://api.instagram.com/v1/';
private token = 'blalba';
constructor (private jsonp: Jsonp) {}
public getTagMedia(tag: String, url: string|null): Promise<Search> {
url = url || `${this.apiUrl}tags/${tag}/media/recent?access_token=${this.token}`;
url = `${url}&callback=JSONP_CALLBACK`
return this.jsonp.get(url)
.toPromise()
.then(response => { return new Search(response.json());})
}
}
搜索模型:
export class Search {
private data;
private metadata;
private pagination;
constructor(row) {
this.data = row.data;
this.metadata = row.metadata;
this.pagination = row.pagination;
}
public getNextUrl(): string | null {
return this.pagination.next_url || null;
}
public getMedia() {
return this.data;
}
}
我知道Observable.flatMap()但由于请求数量未知,在这种情况下无法使用它。
如何获取所有api页面? ps我是Angular 2和js的新手。 pps抱歉我的英文
答案 0 :(得分:0)
我做错了(recursion和Promises)错了。 工作解决方案(服务):
@Injectable()
export class InstagramService {
private apiUrl = 'https://api.instagram.com/v1/';
private token = 'blabla';
private pagesLimit = 5;
constructor (private jsonp: Jsonp) {}
public getTagMedia(tag: string): Promise<Post[]> {
let url = `${this.apiUrl}tags/${tag}/media/recent?access_token=${this.token}`;
url = `${url}&callback=JSONP_CALLBACK`;
return this.getPosts(url, 0);
}
public getPosts(url: string, page: number): Promise<Post[]> {
return this.jsonp.get(url)
.delay(200)
.toPromise()
.then(response => {
let search = new Search(response.json());
let nextUrl = search.getNextUrl();
if (nextUrl && page < this.pagesLimit) {
nextUrl = `${nextUrl}&callback=JSONP_CALLBACK`;
return this.getPosts(nextUrl, ++page)
.then(res => search.getMedia().concat(res))
} else {
return search.getMedia();
}
})
.catch(this.handleError);
}
private handleError (error: Response | any) {
console.log(error);
}
}