以角度将数据从一个打字稿文件传递到另一个[重复]

Posted

技术标签:

【中文标题】以角度将数据从一个打字稿文件传递到另一个[重复]【英文标题】:passing data from one typescript file to another in angular [duplicate] 【发布时间】:2020-01-17 06:59:23 【问题描述】:

我有一个具有以下模板的组件

<div> This is A component </div>
    <router-outlet></router-outlet> 

如果我使用网址

site.com/A/B

然后角度加载 A 组件并将 B 放入 A 的模板中。

一个组件有:

export class SettingsComponent implements OnInit 
  someVar;

 ngOnInit() 
this.someVar = "TEST"

如何在启动 B 组件时获取此变量???

编辑我不想为他们每个人使用服务,因为我从 API 获得了测试。我想我会用这样的请求加载服务器两次。而不是我只想得到它一次。就像在这个例子中一样,假设我从服务器收到回复并将其放入 this.someVar = "TEST" 所以第二个组件应该只使用第一个组件数据而不接触后端服务器 API。

【问题讨论】:

不清楚! site.com/A/B 应该如何工作?你能提供stackblitz吗? 你只是得到一些页面。其中一部分来自组件 A,其余 html 来自 B。当 A 组件加载时,它从后端 API 获取数据。我希望 B 组件在不使用服务的情况下使用来自组件 A 的相同数据。因为我认为服务会加载后端 API 两次 @David 为什么 API 会被调用两次?如果在 root 中提供服务(如下面的回答),这将是一个单例,因此 API 调用将完全由服务调用的次数决定 【参考方案1】:

使用共享服务

工作示例:https://stackblitz.com/edit/angular-fgut7t

服务:

import  Injectable, EventEmitter  from '@angular/core';

@Injectable(
    providedIn: "root"
)
export class DataService 

  dataUpdated:EventEmitter<any> = new EventEmitter();

  constructor()  

  setLatestData(data) 
    this.dataUpdated.emit(data);
  


孩子:

import  Component, OnInit, Input  from '@angular/core';
import  DataService  from '../data-service.service';

@Component(
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
)
export class ChildComponent implements OnInit 

  @Input() allData: [];
  latestData: any;

  constructor(private dataService: DataService)  

  ngOnInit() 
    this.dataService.dataUpdated.subscribe((data) => 
      this.latestData = data;
    );
  


家长:

import  Component  from '@angular/core';
import  DataService  from './data-service.service'

@Component(
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
)
export class AppComponent  
  name = 'Angular';
  dataArr = [];

  constructor(private dataService: DataService)

  onAddTimestamp() 
    let timestamp = new Date();
    this.dataArr.push(timestamp);
    this.dataService.setLatestData(timestamp);
  


【讨论】:

以上是关于以角度将数据从一个打字稿文件传递到另一个[重复]的主要内容,如果未能解决你的问题,请参考以下文章

将数据从 HTML 页面传递到打字稿文件

如何以角度(打字稿)从浏览器获取客户端IP地址

查找和替换打字稿角度

以角度将数据从一个组件传递到另一个组件

在打字稿中创建指令以显示角度加载进度

需要至少一个道具传递给组件[打字稿] [重复]