【问题标题】:Is it correct Inject Component in another在另一个中注入组件是否正确
【发布时间】:2019-10-16 18:09:13
【问题描述】:

我想在另一个组件中调用一些函数,我可以将它注入到当前组件的构造函数中吗?

import { HomeComponent} from './../home/home.component';

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

  constructor(home:HomeComponent){
    home.getSomeData()
  }
}

【问题讨论】:

  • 那么,那段代码编译了吗?跑?那可能会回答你的问题......
  • 非常感谢@jonrsharpe
  • @HereticMonkey 是的,它已编译并成功运行!!

标签: angular typescript components


【解决方案1】:

不,您不能将一个组件注入另一个组件。您应该为此创建一个服务。

您可以使用Behaviour Subject 在两个不相关的组件之间进行通信。

看到这个tutorial

【讨论】:

  • 我是在服务还是组件中创建行为主体?
  • 感谢您的帮助:)
猜你喜欢
  • 2020-01-10
  • 2020-11-17
  • 2018-12-31
  • 2020-02-21
  • 2020-02-07
  • 1970-01-01
  • 2019-02-08
  • 2017-06-17
  • 2022-08-11
相关资源
最近更新 更多