Angular_02_访问API

  • post-list.component.html
<div *ngIf="!pageMeta">
  <p>waitting for response!</p>
</div>
<div *ngIf="pageMeta">
  <ng-container *ngFor='let item of posts'>
      {{item.title}}
  </ng-container> 
</div>
  • post-list.component.ts
export class PostListComponent implements OnInit {
  posts: Post[];
  pageMeta: PageMeta;
  postParameter = new PostParameters({ orderBy: 'id desc', pageSize: 10, pageIndex: 0 });

  constructor(private postService: PostService) { }

  ngOnInit() {
    this.getPosts();
  }

  getPosts() {
    this.postService.getPagedPosts(this.postParameter).subscribe(resp => {
      this.pageMeta = JSON.parse(resp.headers.get('X-Pagination')) as PageMeta;
      const result = { ...resp.body } as ResultWithLinks<Post>;
      this.posts = result.values;
    });
  }
}
  • service
export class PostService extends BaseService {

  constructor(private http: HttpClient) {
    super();
  }

  getPagedPosts(postParameter?: any | PostParameters) {
    return this.http.get(`${this.apiUrlBase}/posts`, {
      headers: new HttpHeaders({ 'Accept': 'application/vnd.enfi.hateoas+json' }),
      observe: 'response',
      params: postParameter
    });
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容