首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在模块联邦中以角创建服务的单个实例?

如何在模块联邦中以角创建服务的单个实例?
EN

Stack Overflow用户
提问于 2022-09-28 07:21:10
回答 1查看 124关注 0票数 0

我用这里提供的回购工具重新创建了这个问题:https://github.com/module-federation/module-federation-examples/tree/master/angular13-microfrontends-lazy-components

默认情况下,mdmf共享服务没有被使用,所以我尝试使用它,但注意到为mdmf-shell和mdmf-profile创建服务的两个独立实例。我已经通过记录构造函数调用和一些本地类值来确认这一点。构造函数被调用两次,传递给实例的两个值都不为另一个应用程序所知。这是我添加的代码--我做错了什么?

mdmf-shared.service.ts

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { MdmfSharedModule } from '../modules/mdmf-shared.module';

@Injectable({
  providedIn: MdmfSharedModule, // I've also tried providedIn: 'root' and 'platform' same result
})
export class MdmfSharedService {
  private count: number = 0;
  private word: string = '';
  constructor() {
    console.log(this.count++)
  }

  ping(word?: string) {
    console.log('pinging mdmf shared service')
    this.word = word;
    console.log('this is the word: ', word)
  }
}

mdmf-shared.module.ts

代码语言:javascript
复制
import { NgModule } from '@angular/core';
import { MdmfSharedComponent } from '../components/mdmf-shared.component';
import { CommonModule } from '@angular/common';

@NgModule({
  // declarations: [MdmfSharedComponent, ListUserComponent],
  declarations: [MdmfSharedComponent],
  imports: [CommonModule],
  // exports: [MdmfSharedComponent, ListUserComponent]
  exports: [MdmfSharedComponent],
})
export class MdmfSharedModule {}

app.module(mdmf-shell)

代码语言:javascript
复制
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { ShellModule } from './shell/shell.module';
import { AppComponent } from './app.component';
import { APP_ROUTES } from './app.routes';
import { MicrofrontendService } from './microfrontends/microfrontend.service';
import { MdmfSharedModule } from 'projects/mdmf-shared/src/lib/modules/mdmf-shared.module';
import { NgxsModule } from '@ngxs/store';
import { UserState } from 'projects/mdmf-shared/src/lib/app-state/state/user.state';

export function initializeApp(mfService: MicrofrontendService): () => Promise<void> {
  return () => mfService.initialise();
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    RouterModule.forRoot(APP_ROUTES),
    NgxsModule.forRoot([UserState]),
    MdmfSharedModule,
  ],
  providers: [
    MicrofrontendService,
    {
      provide: APP_INITIALIZER,
      useFactory: initializeApp,
      multi: true,
      deps: [MicrofrontendService],
    }
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

app.component.ts(mdmf-shell)

代码语言:javascript
复制
import { Component } from '@angular/core';
import { MdmfSharedService } from 'projects/mdmf-shared/src/public-api';
import { MicrofrontendService } from './microfrontends/microfrontend.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'mdmf-shell';
  constructor(public mfService: MicrofrontendService, public mdmfSharedService: MdmfSharedService) {
    mdmfSharedService.ping() // first instance
  }
}

app.module.ts(mdmf-profile)不导入mdmf-shared.module或服务

profile.component.ts(mdmf-profile)

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { AddUser } from 'projects/mdmf-shared/src/lib/app-state/actions/user.action';
import { User } from 'projects/mdmf-shared/src/lib/app-state/models/User';
import { MdmfSharedService } from 'projects/mdmf-shared/src/lib/services/mdmf-shared.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css'],
})
export class ProfileComponent implements OnInit {
  angForm: FormGroup;

  ngOnInit(): void {}

  constructor(private fb: FormBuilder, private store: Store, public mdmfSharedService: MdmfSharedService) {
    mdmfSharedService.ping() // second instance
    this.angForm = this.createForm();
  }

  /**
   * Initialize the form
   */
  createForm(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
    });
  }

  /**
   * Handle the add user when the 'Create User' button is clicked
   * @param name: user's name
   * @param email: user's email
   */
  addUser(name: string, email: string): void {
    this.store.dispatch(new AddUser({ name, email } as User));
  }

  /**
   * Get the users for unit testing purposes
   */
  getUsers(): User[] {
    return this.store.selectSnapshot<User[]>(state => state.users.users);
  }
}

webpack.config.js(mdmf-shell)

代码语言:javascript
复制
const webpack = require('webpack');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');

module.exports = {
  output: {
    publicPath: 'http://localhost:4200/',
    uniqueName: 'shell',
    scriptType: 'text/javascript',
  },
  optimization: {
    runtimeChunk: false,
  },
  plugins: [
    new ModuleFederationPlugin({
      remotes: {
        profile: 'profile@http://localhost:4201/remoteEntry.js}',
      },
      shared: {
        '@angular/core': { eager: true, singleton: true },
        '@angular/common': { eager: true, singleton: true },
        '@angular/router': { eager: true, singleton: true },
        '@ngxs/store': { singleton: true, eager: true },
        'mdmf-shared': { singleton: true, eager: true },
      },
    }),
  ],
};

webpack.config.js(mdmf-profile)

代码语言:javascript
复制
const webpack = require('webpack');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');

module.exports = {
  output: {
    publicPath: 'http://localhost:4201/',
    uniqueName: 'mdmfprofile',
    scriptType: 'text/javascript',
  },
  optimization: {
    runtimeChunk: false,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'profile',
      library: { type: 'var', name: 'profile' },
      filename: 'remoteEntry.js',
      exposes: {
        ProfileModule: './projects/mdmf-profile/src/app/profile/profile.module.ts',
      },
      shared: {
        '@angular/core': { singleton: true, eager: true },
        '@angular/common': { singleton: true, eager: true },
        '@angular/router': { singleton: true, eager: true },
        '@ngxs/store': { singleton: true, eager: true },
        'mdmf-shared': { singleton: true, eager: true },
      },
    }),
  ],
};
EN

回答 1

Stack Overflow用户

发布于 2022-09-28 23:55:59

我解决了自己的问题,我面临的问题是使用yarn link而不是在tsconfig.json中将lib添加到编译器选项中。

我的理论是,纱线链接消除了库的可见性(而不是模拟符号链接的参与),因此从编译和webpack的shareAll功能的配置中删除了它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73877632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档