简体   繁体   English

将数据传递到包中的Angular 4组件中

[英]Passing data into Angular 4 component that is in a package

I am creating NPM packages of Angular 4 modules/components/services. 我正在创建Angular 4模块/组件/服务的NPM软件包。 The component needs to display things that are app-specific like the user name and an environment-specific URL or two. 该组件需要显示特定于应用程序的内容,例如用户名和一个或两个特定于环境的URL。

I'm having trouble determining how I would pass that data from my Angular 4 app into these shared components. 我在确定如何将数据从Angular 4应用程序传递到这些共享组件时遇到麻烦。 I tried creating a service inside the component and using Subject but that didn't work because it was creating a copy of the service for both the package component and the app component. 我尝试在组件内部创建服务并使用Subject,但这没有用,因为它正在为包组件和app组件创建服务的副本。

So my question is: Is this even possible using Angular 4? 所以我的问题是:使用Angular 4甚至可能吗? If so, how? 如果是这样,怎么办?

Answering my own question here. 在这里回答我自己的问题。 It turns out it is possible to share a service that lives in an npm packaged Angular 4 component/module/service with your app. 事实证明,可以与您的应用共享一个位于npm打包的Angular 4组件/模块/服务中的服务。

What I was doing was not binding my packaged component variables correctly, ie using the async pipe and binding directly to the Subject<string>. 我正在做的是没有正确绑定打包的组件变量,即使用异步管道并直接绑定到Subject <string>。 I was handling the subscribing and that didn't work properly. 我正在处理订阅,但工作不正常。

Here's the html in the packaged component: 这是打包组件中的html:

<p>Welcome, <b>{{fullName | async}}</b>

Then in the component typescript file: 然后在组件打字稿文件中:

ngOnInit(): void {
    this.fullName = this.headerSvc.nameSource;
}

The headerSvc has this: headerSvc具有:

public nameSource:Subject<string> = new BehaviorSubject<string>("");

and this (which the app calls): 这(应用调用):

setName(name: string) {
  this.nameSource.next(name);
}

Hope this helps someone figure this out. 希望这可以帮助某人解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM