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

标签 javascript angular typescript angular2-forms angular2-ngmodel

考虑一个简单的增删改查场景。我在 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>

我只想从 get-one-post-id 字段中获取值,从 app.component.htmlpost-by-id- component.ts [我评论的地方//const id = ??]。但我找不到导入它的方法。

最佳答案

在 Angular 组件之间共享数据有 4 种不同的方式:

  1. 父对子:通过输入共享数据

  2. 子级到父级:通过 ViewChild 共享数据

  3. 子级到父级:通过 Output() 和 EventEmitter 共享数据
  4. 不相关的组件:与服务共享数据

您可以阅读this有用的文章来了解它是如何工作的。

关于javascript - Angular:如何从一个组件前端(app.component.html)到另一组件后端(other.component.ts)获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058498/

相关文章:

javascript - 如何在 HTML 链接中使用 JavaScript 变量

javascript - 修复 AngularJS 1.2.0 [$parse :isecprv] errors

javascript - Ionic2、Angular2、HTTP 和 Observables

Angular 2 i18n 提取失败错误

angular - AOT 编译器 - 包括延迟加载的外部模块

javascript - 如何通过 Angular-cli@webpack 使用 Django

require - 如果我使用 `module("somelib")` in typescript, it can' t 在浏览器中运行

javascript - 对齐三个按钮,使它们位于两个 Bootstrap Jumbotron 容器的底部

Javascript - 按类(class)获得跨度?

angular - Keycloak-angular : access/account fails with 403 error and CORS message