无法使Angular 5 StateTransfer工作

时间:2018-05-12 03:04:14

标签: angular

我不能为我的生活让Angular StateTransfer工作。我已经关注了六个不同的教程并将其归结为最简单的示例,它将无法正常工作。没有那么多工件,我只是不确定我做错了什么。状态键永远不会通过。所以我从未点过第一个if语句,它总是空的。

以下是我的所有课程。

更新: 所以我仍然没有这个工作,但我注意到包含服务器状态的标签确实存在。

<script id="fhh-app-state" type="application/json">{&q;featured_key&q;:&q;Im created on the server!&q;}</script>

但由于某种原因,国家无法看到它。

home.component.ts

    const FEATURE_KEY = makeStateKey('featured_key');

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  posts: Observable<IPost[]>;

  public result;
  private isServer: boolean;

  constructor(private postService: PostService,
              private state: TransferState,
              @Inject(PLATFORM_ID) platformId: Object) {

                this.isServer = isPlatformServer(platformId);
               }

  ngOnInit() {

    console.log('state key', this.state.get(FEATURE_KEY, 'default'));

    if (this.state.hasKey(FEATURE_KEY)) {
      console.log('state 1');
      // We are in the browser
      this.result = this.state.get(FEATURE_KEY, '');
    } else if (this.isServer) {
        console.log('state 2');
        // We are on the server
        this.state.set(FEATURE_KEY, 'Im created on the server!' as any);
    } else {
        console.log('state 3');
        // No result received 
        this.result = 'Im created in the browser!';
    }

  }

}

server.ts

const app = express();
const compression = require('compression');

app.use(compression());

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');

const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

app.engine('html', (_, options, callback) => {
  renderModuleFactory(AppServerModuleNgFactory, {
    document: template,
    url: options.req.url,
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP)
    ]
  }).then(html => {
    callback(null, html);
  });
});

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { BrowserModule } from '@angular/platform-browser';

import {AppModule} from './app.module';
import {AppComponent} from './app.component';

@NgModule({
  imports: [
    // BrowserModule.withServerTransition({appId: 'fhh-app'}),
    AppModule,
    ServerModule,
    ServerTransferStateModule, //  <-- needed for state transfer
    ModuleMapLoaderModule // <-- *Important* to have lazy-loaded routes work
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule.withServerTransition({appId: 'fhh-app'}),
    BrowserTransferStateModule,
    ...
    ServiceWorkerModule.register('/ngsw-worker.js', {enabled: environment.production})
    ...
  ],
  providers: [
    CanDeactivateGuard,
    CancelDialogService,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:1)

好的,所以我终于弄明白了我的问题。几乎所有的教程都遗漏了关键的一步。您必须向main.ts文件添加代码以侦听要加载的DOM。以下是我必须添加以使其正常工作的内容。

document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
    if ('serviceWorker' in navigator && environment.production) {
      navigator.serviceWorker.register('/ngsw-worker.js');
    }
  })
    .catch(err => console.log(err));
});

希望这有助于某人!