如何使用一个按钮为列表中的每个帖子获取一条评论?

时间:2019-02-20 19:48:11

标签: javascript rxjs httpclient

女巫api用于获取帖子和评论。 HttpClient的get方法用于连接到wordpresss api。我遇到的两个问题是,仅在完成上一个帖子时才获取列表中下一个帖子的下一个评论,第二个问题是在每个特定帖子下显示每个唯一响应(评论)的方式。这是我所拥有的:

app.module.ts

import { AppComponent } from './app.component';
import { PostsComponent } from './posts/posts.component';
import { CommentComponent } from './comment/comment.component';


@NgModule({
 declarations: [
    AppComponent,
    PostsComponent,
    CommentComponent
],
 imports: [
   BrowserModule,
   HttpClientModule
],
 providers: [ CommentComponent ],
 bootstrap: [AppComponent]
})

comment.component.ts

export class CommentComponent implements OnInit {
@Input() post: Object
comment$: Object
constructor(private commentService: CommentService) { }

getCommentPost(posts) {
    this.commentService.setPosts(posts);
    this.commentService.getPostComment()
    .subscribe(
    comment => this.comment$ = comment,
    err => console.error('error: ', err),
    () => console.log('completed')
   )
}

comment.service.ts

interface Comment {
   content: string,
   date: Date
}

interface Response {
   comments: Comment[]
}

interface post {
   ID: number,
   site_ID: number
}

@Injectable({
  providedIn: 'root'
})

export class CommentService {
  posts: post[]
  constructor(private http: HttpClient) { }

  setPosts(posts) {
      this.posts = posts;
      this.getPostComment();
  }

  getPostComment() {
      return this.http.get<Response>(`https://public-api.wordpress.com/rest/v1.1/sites/${this.posts[0].site_ID}/posts/${this.posts[0].ID}/replies?number=1`)
  .pipe(
    filter(data => data.comments.length !== 0),
    map(data => data.comments[0]),
    mergeMap((c) => this.http.get<Response>(`https://public-api.wordpress.com/rest/v1.1/sites/${this.posts[1].site_ID}/posts/${this.posts[1].ID}/replies?number=1`)),
    map(data => data.comments[1]),
    mergeMap((c) => this.http.get<Response>(`https://public-api.wordpress.com/rest/v1.1/sites/${this.posts[2].site_ID}/posts/${this.posts[2].ID}/replies?number=1`)),
    map(data => data.comments[2]),
    retry(3),
    shareReplay()
  )
 }   
}

在posts.component.html中,

<button (click)="comment.getCommentPost(posts$)">Get Comment per Post</button>

在comment.component.html中,

<div *ngIf="comment$ !== undefined">
    <p [innerHTML]="comment$.content">
    {{comment$.ID}}
    </p>
</div>

我通过angular-cli命令创建了项目。

0 个答案:

没有答案