簡體   English   中英

Angular2將API數據傳遞給另一個組件

[英]Angular2 passing API data to another component

TL; DR:我想將html模板中的變量從一個組件傳遞到另一個。 docs: <my-comment (blogId)="blog.id"></my-comment>描述了類似的內容,並且沒有錯誤提示。 但是如何在其他組件中“緩存”此變量? 我想將博客ID作為變量傳遞給API。

加長版:我制作了一個Angular2,其中包含兩個帶有Parent-Child組件和一個單獨組件。 它們是:博客列表(帖子列表),一個帖子和評論。

我嘗試將從博客API檢索博客ID傳遞給注釋組件,然后放入其API。

所以我有:comments.service

(...)    
@Injectable()
export class CommentsService {
    constructor(private http: Http) {}
        private headers = new Headers({'Content-Type': 'application/json'});

    create(body: string, author: string, date: string, post: any): Promise<Comments> {
        return this.http
            .post(API_ENDPOINT, JSON.stringify({body: body, name: author, date: date, postId: post}), {headers: this.headers})
            .toPromise()
            .then(this.extractData);
    }

    (...)
}

comments.component,出現Ts錯誤:提供的參數與調用目標的任何簽名都不匹配。 在這條線上:(但是應用程序和API可以正常工作)。

this.commentsService.create(正文,名稱,日期,postId)

import {Component, ViewEncapsulation, OnInit, OnDestroy, NgModule, Input} from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import 'rxjs/add/operator/toPromise';
import {CommentsService} from "./comments.service";
import {Comments} from "./comments.model";
import {PostComponent} from '../blog/post.component';
import { BlogService } from '../blog/blog.service';

@Component({
    selector: 'my-comment',
    templateUrl: './comments.html',
    styleUrls: ['./comments.scss'],
    encapsulation: ViewEncapsulation.None,
    providers: [CommentsService]
})

@NgModule({
    declarations: [PostComponent]
})

export class CommentsComponent implements OnInit, OnDestroy {
    private postId: Comments;
    private body: Comments;
    private name: Comments;
    private date: any = new Date().toLocaleString();
    private postComponent: any = PostComponent;
    private blog: any = BlogService;

    constructor(
        private route: ActivatedRoute,
        private commentsService: CommentsService
    ) {

    }

    ngOnInit(): void {
        let id = +this.route.snapshot.params['id'];
    }

    ngOnDestroy(): void {}

    add(body: string, name: string, date: string, postId: number): void {
        body = body.trim();
        name = name.trim();
        if (!body || !postId || !name) { return; }
        this.commentsService.create(body, name, date, postId);
    }
}

我要在其中包含博客ID變量的Comment.html模板。

<div ngclass="form" class="form">
    <!--<input #name />-->
    <p ngClass="form__title">We are thrilled to hear your opinion:</p>
    <input #body ngClass="form__body" placeholder="Put your text here" />
    <input #name placeholder="Your name" />

    <button class="btn btn-1 btn-1d" (click)="add(body.value, name.value, date, ????blogPostID????); body.value=''; name.value='';">
        Add
    </button>
</div>

從具有ID的API中檢索博客文章,並通過其父組件中的* ngFor進行迭代。 在post.component中,我提供了注釋服務,因此該模板非常適合一篇文章(post.html):

    <article *ngIf="blog" class="post">
    <header>
        <h2>{{ blog.id }}\ {{ blog?.title }}</h2>
    </header>
    <section class="article__content">
        {{ blog?.text }}
        <p class="author"> {{ blog?.name }}</p>
    </section>
    <footer>
        <a [routerLink]="['/blog']" routerLinkActive="active" class="btn btn-1 btn-1e">Return</a>
    </footer>
</article>

<section *ngIf="comments" class="comment">
    <h2>Comments:</h2>
    <main>
        <div *ngFor="let comment of comments">
            <div *ngIf="comment.postId == blog.id">
                <p>{{ comment.body }}</p>
                <p>{{ comment.postId }}</p>
            </div>
        </div>
        </main>
</section>

<my-comment></my-comment>

但是我想提供從單個帖子(* ngFor迭代組件)到某種方式的blog.id。

對我的問題的回答很簡單,但花了我一些時間才能將它們放在一起。

要將變量傳遞給另一個組件,請在父模板中使用:另一個組件在哪里,blog.id是要傳遞給的變量。

    <my-comment [blogId]="blog.id"></my-comment>

在注釋組件中,我添加了導入:

export class CommentsComponent implements OnInit, OnDestroy {        
@Input() blogId:number;
...

然后,我可以在評論模板中使用blogId變量,它是post組件中blog.id的精確副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM