我正在尝试使用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
My APP
知道我在哪里弄错了吗?
答案 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)