离子角中的HttpErrorResponse

时间:2019-05-23 01:26:54

标签: angular ionic-framework

我正在尝试使用Ionic(首次尝试),但由于某种原因,我无法在视图中获取数据

代码

Service (posts.service.ts)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class PostsService {

  apiUrl = 'https://example.com/api/posts/';
  url: any;

  constructor(private http: HttpClient) { }

  getPosts(): Observable<any> {
    return this.http.get(`${this.apiUrl}`).pipe(
      map(posts => posts)
    );
  }

  getDetails(url) {
    return this.http.get(`${this.url}?i=${url}&plot=full`);
  }
}

Controller (posts.page.ts)

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { PostsService } from './../../services/posts.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.page.html',
  styleUrls: ['./posts.page.scss'],
})
export class PostsPage implements OnInit {

  posts: Observable<any>;

  constructor(private postsService: PostsService) {}

  ngOnInit() {
  }

}

view (posts.page.html)

<ion-list>
  <ion-item *ngFor="let post of posts">
    <div slot="start"></div>
    <img [src]="post.image" />
    {{post.title}}
    <div class="item-note" slot="end">
      {{post.body}}
    </div>
  </ion-item>
</ion-list>

输出

Live API

one

My APP

two

知道我在哪里弄错了吗?

3 个答案:

答案 0 :(得分:0)

您需要在控制器上调用getPosts()

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { PostsService } from './../../services/posts.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.page.html',
  styleUrls: ['./posts.page.scss'],
})
export class PostsPage implements OnInit {

  posts: Observable<any>;

  constructor(private postsService: PostsService) {}

  ngOnInit() {
      this.posts = this.postsService.getPosts();
  }

}

在您的html中,您还需要指定async

<ion-item *ngFor="let post of posts | async">

答案 1 :(得分:0)

您应该订阅可观察对象以获得结果。 Observables是Lazy,除非您订阅,否则不会发起呼叫。您可以使用有角度的 async 管道,该管道会自动为您订阅和取消订阅

 <ion-item *ngFor="let post of getPosts() | async">
    <div slot="start"></div>
    <img [src]="post.image" />
    {{post.title}}
    <div class="item-note" slot="end">
      {{post.body}}
    </div>
  </ion-item>

或者您可以从组件本身订阅。

    posts:any;
    ngOnInit() {
    this.poseService.getPosts().suscribe((res)=>{
      this.posts=res;
    })
    }
 <ion-item *ngFor="let post of posts">

答案 2 :(得分:0)

已解决

请参考我解决该问题的其他问题。

Ionic can't get open cors