【问题标题】:Angular2 passing API data to another componentAngular2将API数据传递给另一个组件
【发布时间】:2016-12-21 12:21:55
【问题描述】:

TL;DR: 我想将 html 模板中的变量从一个组件传递到另一个组件。 文档中描述了这样的事情:<my-comment (blogId)="blog.id"></my-comment> 并且没有错误。但是如何在其他组件中“缓存”这个变量?我想将博客 ID 作为变量传递给 API。

加长版: 我制作了一个 Angular2,它有两个组件,一个是父子组件,一个是独立组件。它们是:博客列表(list of post)、一篇文章和cmets。

我尝试将从博客 API 检索到的博客 ID 传递给 cmets 组件并放入其 API。

所以我有: cmets.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);
    }

    (...)
}

cmets.component,我有一个 Ts 错误: 提供的参数与调用目标的任何签名都不匹配。 在这一行:(但应用程序和 API 工作正常)。

this.cmetsService.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 模板,我想要一个博客 ID 变量。

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

博客文章从 API 中检索到 Id 并由 *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。

【问题讨论】:

    标签: angular typescript angular2-http


    【解决方案1】:

    我的问题的答案很简单,但我花了一些时间来整理所有内容。

    要将变量传递给我在父模板中使用的另一个组件:另一个组件在哪里,而 blog.id 是要传递给的变量。

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

    在 cmets 组件中我添加了导入:

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

    然后我可以在评论模板中使用blogIdvariable,它是帖子组件中 blog.id 的精确副本。

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2018-01-16
      • 2018-10-21
      • 2018-05-02
      • 2017-06-01
      相关资源
      最近更新 更多