Angular:如何从一个组件的前端(app.compont.html)到另一个组件的后端(other.component.ts)获取价值

问题描述 投票:0回答:1

考虑一个简单的粗略方案。 app.component.html中有很多输入字段和按钮。当我按下app.component.html中的按钮时,它将html字段值发送到'other.component.ts'组件,并在处理(如加,减或其他)后将结果显示回app.component.html中。

这里是app.component.html

<a routerLink="posts/">Show Posts</a>
<input type="number" [(ngModel)]="get-one-post-id">
<a routerLink="/post-by-id">Show One Posts</a>


<router-outlet>

</router-outlet>

post-by-id-component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-post-by-id',
  templateUrl: './post-by-id.component.html',
  styleUrls: ['./post-by-id.component.css']
})
export class PostByIdComponent implements OnInit {

  posts: object;
  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    // const id = ??
    this.GetPost(1);
  }

  async GetPost(id: number)
  {
    const response = await this.dataService.Get_A_Post(id);
    const dataService = await response.json();
    this.posts = dataService;
  }

}

post-by-id-component.html

<div *ngFor="let post of posts">
  <h3>{{post.title}}</h3>
  <p>{{post.body}}</p>
</div>

我只想从app.component.html

post-by-id-component.tsget-one-post-id字段中获取价值评论// const id = ??]。但是我找不到导入它的方法。

考虑一个简单的粗略方案。我在app.component.html中有很多输入字段和按钮。当我按下app.component.html中的按钮时,它将html字段值发送到'other.component.ts'...

javascript angular typescript angular2-forms angular2-ngmodel
1个回答
1
投票

到Angular Components之间的sharedData存在4种不同的方式:

© www.soinside.com 2019 - 2024. All rights reserved.