简体   繁体   中英

Angular2 passing API data to another component

TL;DR: I want to pass a variable in html template from one component to another. Something like this is described in docs: <my-comment (blogId)="blog.id"></my-comment> and trows no error. But how to 'cach' this variable in other component? I want to pass blog Id as variable to API.

Long version: I've made an Angular2 with two components with Parent-Child and one separate. They are: blog list (list of post), one single post and comments.

I try to pass a blog id retrieve from blog API to comments component and put to its API.

So I have: 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, where I've got a Ts error: Supplied parameters do not match any signature of call target. On this line: (but application and API works fine).

this.commentsService.create(body, name, date, 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);
    }
}

Comments.html template where I want to have an blog Id variable.

<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>

Blog Post are retrieved from API with Id and iterate by *ngFor in its Parent Component. In post.component I provided a Comments Service, so this template works very well for one post (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>

But I want to provide a blog.id from single post (*ngFor iterated component) to somehow.

Answer to my question was very simple but took me some time to put all together.

To pass a variable to another component I use in parent template: Where is an other component and blog.id an variable to pass to.

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

In comments component I added import:

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

And then I can use a blogId variable in comment template and it's a exact copy of blog.id in post component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM