@angular/common#APP_BASE_HREF TypeScript Examples

The following examples show how to use @angular/common#APP_BASE_HREF. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: prerender.ts    From ng-event-plugins with Apache License 2.0 6 votes vote down vote up
// Iterate each route path
PRERENDERED_ROUTES.forEach(route => {
    const fullPath = join(DEMO_FOLDER, route);

    // Make sure the directory structure is there
    if (!existsSync(fullPath)) {
        mkdirSync(fullPath);
    }

    // Writes rendered HTML to index.html, replacing the file if it already exists.
    previousRender = previousRender
        .then(() =>
            renderModuleFactory(AppServerModuleNgFactory, {
                document: index,
                url: route,
                extraProviders: [
                    provideModuleMap(LAZY_MODULE_MAP),
                    {
                        provide: APP_BASE_HREF,
                        useValue: process.env.ORIGIN || localFallback,
                    },
                ],
            }),
        )
        .then(html => writeFileSync(join(fullPath, 'index.html'), html));
});
Example #2
Source File: server.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
/**
 * In order for angular to work with SSR with an already existing express app,
 * call this init to mount angular in SSR mode.
 * @param server The express app we want to mount angular SSR into
 * @param distFolder The angular browser dist directory where angular was compiled to
 */
export function init(server: express.Application, distFolder: string): void {
  const indexHtml = existsSync(join(distFolder, 'index.original.html'))
    ? 'index.original.html'
    : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine(
    'html',
    ngExpressEngine({
      bootstrap: AppServerModule,
    })
  );

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Serve static files from /browser
  server.get(
    '*.*',
    express.static(distFolder, {
      maxAge: '1y',
    })
  );

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, {
      req,
      providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
    });
  });
}
Example #3
Source File: app.module.ts    From client-side-databases with Apache License 2.0 6 votes vote down vote up
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ChatModule
  ],
  providers: [
    { provide: APP_BASE_HREF, useValue: '/' },
    {
      provide: LocationStrategy,
      useClass: PathLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Example #4
Source File: app.module.ts    From client-side-databases with Apache License 2.0 6 votes vote down vote up
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ChatModule
  ],
  providers: [
    { provide: APP_BASE_HREF, useValue: '/' },
    {
      provide: LocationStrategy,
      useClass: PathLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Example #5
Source File: app.module.ts    From client-side-databases with Apache License 2.0 6 votes vote down vote up
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ChatModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: () => initDatabase,
      multi: true,
      deps: [/* your dependencies */]
    },
    DatabaseService,
    { provide: APP_BASE_HREF, useValue: '/' },
    {
      provide: LocationStrategy,
      useClass: PathLocationStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Example #6
Source File: app.browser.module.ts    From resize-observer with MIT License 6 votes vote down vote up
@NgModule({
    bootstrap: [AppComponent],
    imports: [
        CommonModule,
        FormsModule,
        BrowserModule.withServerTransition({appId: 'demo'}),
        AppRoutingModule,
        ResizeObserverModule,
        ReactiveFormsModule,
    ],
    declarations: [AppComponent],
    providers: [
        {
            provide: LocationStrategy,
            useClass: PathLocationStrategy,
        },
        {
            provide: APP_BASE_HREF,
            useValue: '',
        },
    ],
})
export class AppBrowserModule {}
Example #7
Source File: app.browser.module.ts    From canvas with MIT License 6 votes vote down vote up
@NgModule({
    bootstrap: [AppComponent],
    imports: [
        CommonModule,
        FormsModule,
        CanvasModule,
        BrowserModule.withServerTransition({appId: 'demo'}),
        AppRoutingModule,
    ],
    declarations: [AppComponent],
    providers: [
        {
            provide: LocationStrategy,
            useClass: PathLocationStrategy,
        },
        {
            provide: APP_BASE_HREF,
            useValue: '',
        },
    ],
})
export class AppBrowserModule {}
Example #8
Source File: server.ts    From open-source with MIT License 6 votes vote down vote up
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/website/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}
Example #9
Source File: app.module.ts    From IntelOwl-ng with GNU Affero General Public License v3.0 6 votes vote down vote up
@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,
    NbEvaIconsModule,
    NbSidebarModule.forRoot(),
    NbMenuModule.forRoot(),
    NbToastrModule.forRoot(),
    CoreModule.forRoot(),
    ThemeModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [
    AuthGuard,
    ToastService,
    DexieService,
    IndexedDbService,
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
    { provide: APP_BASE_HREF, useValue: '/' },
  ],
})
export class AppModule {}
Example #10
Source File: server.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
// The Express app is exported so that it can be used by serverless Functions.
export function app(): void {
  const server = express()
  const distFolder = join(process.cwd(), 'dist/formatter/browser')
  const indexHtml = existsSync(join(distFolder, 'index.original.html'))
    ? 'index.original.html'
    : 'index'

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine(
    'html',
    ngExpressEngine({
      bootstrap: AppServerModule,
    })
  )

  server.set('view engine', 'html')
  server.set('views', distFolder)

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get(
    '*.*',
    express.static(distFolder, {
      maxAge: '1y',
    })
  )

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, {
      req,
      providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
    })
  })

  return server
}
Example #11
Source File: server.ts    From oss-github-benchmark with GNU General Public License v3.0 6 votes vote down vote up
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/oss-github-benchmark/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}
Example #12
Source File: server.ts    From fab-menu with MIT License 6 votes vote down vote up
// The Express app is exported so that it can be used by serverless Functions.
export function app() {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // app.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}
Example #13
Source File: server.ts    From svvs with MIT License 6 votes vote down vote up
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express()
  const distFolder = join(process.cwd(), 'dist/frontend-client/browser')
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index'

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }))

  server.set('view engine', 'html')
  server.set('views', distFolder)

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y',
  }))

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, {
      req, providers: [
        {provide: APP_BASE_HREF, useValue: req.baseUrl},
        {provide: REQUEST, useValue: req},
        {provide: RESPONSE, useValue: res},
      ],
    })
  })

  return server
}
Example #14
Source File: app.browser.module.ts    From ng-event-plugins with Apache License 2.0 6 votes vote down vote up
@NgModule({
    bootstrap: [AppComponent],
    imports: [
        BrowserModule.withServerTransition({appId: 'demo'}),
        EventPluginsModule,
        AppRoutingModule,
        StaticModule,
        HighlightModule,
    ],
    declarations: [AppComponent],
    providers: [
        {
            provide: LocationStrategy,
            useClass: PathLocationStrategy,
        },
        {
            provide: APP_BASE_HREF,
            useValue: '',
        },
        {
            provide: HIGHLIGHT_OPTIONS,
            useValue: {
                coreLibraryLoader: () => import('highlight.js/lib/core'),
                lineNumbersLoader: () => import('highlightjs-line-numbers.js'), // Optional, only if you want the line numbers
                languages: {
                    typescript: () => import('highlight.js/lib/languages/typescript'),
                    less: () => import('highlight.js/lib/languages/less'),
                    xml: () => import('highlight.js/lib/languages/xml'),
                },
            },
        },
    ],
})
export class AppBrowserModule {}
Example #15
Source File: default.module.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        NgxSpinnerModule,
        SharedModule,
        ComponentsModule,
        EffectsModule.forRoot([ListsEffect]),
        StoreModule.forRoot(reducers, {metaReducers}),
        EffectsModule.forRoot([ListsEffect, WishlistEffect]),
        ShareButtonModule.withConfig({
            debug: true
        }),
        AgmCoreModule.forRoot({
            apiKey: 'AIzaSyCfuTV5tYInC-Mj6YJ9LzRocVOdn3yCUGM'
        }),
        DefaultRoutingModule
    ],
    declarations: [
        DefaultComponent,
        NotFoundComponent,
        DetailPageComponent,
        CONTAINERS.LayoutContainerComponent,
        UnderDevelopingComponent
    ],
    providers: [
        AppSettings,
        LayoutAuthGuard,
        AuthGuard,
        ConfigService,
        {provide: OverlayContainer, useClass: CustomOverlayContainer},
        {provide: MAT_MENU_SCROLL_STRATEGY, useFactory: menuScrollStrategy, deps: [Overlay]},
        {
            provide: HTTP_INTERCEPTORS,
            useClass: RequestInterceptor,
            multi: true
        },
        {provide: APP_BASE_HREF, useValue: ''},
        ListsSandbox,
        ListsService,
        WishlistSandbox,
        WishlistService
    ],
    bootstrap: [DefaultComponent]
})
export class DefaultModule {
}
Example #16
Source File: webcomponent.module.ts    From taiga-front-next with GNU Affero General Public License v3.0 5 votes vote down vote up
@NgModule({
  declarations: [],
  imports: [
    LegacyModule,
    HttpClientModule,
    BrowserModule,
    StoreModule.forRoot({}, {
      runtimeChecks: {
        strictStateImmutability: true,
        strictActionImmutability: true,
        strictStateSerializability: true,
        strictActionSerializability: true,
        strictActionTypeUniqueness: true,
      },
    }),
    extModules,
    EffectsModule.forRoot([]),
    ReactiveComponentModule,
    TextEditorModule,
    ProjectNavigationModule,
    TranslateModule.forRoot(),
    RouterTestingModule.withRoutes([
      {
        path: '**',
        component: EmptyComponent,
      },
    ]),
  ],
  providers: [
    {provide: APP_BASE_HREF, useValue: '/'},
    {
      provide: APP_INITIALIZER,
      multi: true,
      deps: [ConfigService, TranslateService],
      useFactory: (appConfigService: ConfigService, translate: TranslateService) => {
        return () => {
          return appConfigService.fetch().then((config) => {
            translate.setDefaultLang(config.defaultLanguage);
            translate.use(config.defaultLanguage);

            return config;
          });
        };
      },
    },
  ],
})
export class WebcomponentModule {
  constructor(private injector: Injector) {}

  ngDoBootstrap() {
    for (const component of componentes) {
      const strategyFactory = new ElementZoneStrategyFactory(component[1], this.injector);
      const el = createCustomElement(component[1], {injector : this.injector, strategyFactory});

      customElements.define(component[0], el);
    }
  }
}
Example #17
Source File: stories-helper.ts    From taiga-front-next with GNU Affero General Public License v3.0 5 votes vote down vote up
ConfigureStory = (config: {
  component: any,
  title: string,
  declarations?: any[],
  extraModules?: any[],
  routing?: boolean,
  translations?: boolean,
}) => {
  config = {
    declarations: [],
    extraModules: [],
    routing: true,
    translations: true,
    ...config,
  };

  const metadata = {
    declarations: [
      TgSvgSpriteComponent,
      ...config.declarations,
    ],
    providers: [
      {
        provide: LegacyService, useClass: LegacyServiceMock,
      },
    ],
    imports: [
      ...config.extraModules,
    ],
  };

  if (config.routing) {
    metadata.providers.push({provide: APP_BASE_HREF, useValue: '/'});
    metadata.imports.push(
      // Prevent Storybook error "Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'iframe.html'"
      RouterModule.forRoot([], { useHash: true })
    );
  }

  if (config.translations) {
    metadata.imports.push(
      // Add local translations from assets/i18n/en.json
      StoryBookTranslationModule()
    );
  }

  return {
    title: config.title,
    component: config.component,
    decorators: [
      moduleMetadata(metadata),
    ],
  };
}
Example #18
Source File: server.ts    From ng-conf-2020-workshop with MIT License 4 votes vote down vote up
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/ng-conf-workshop-2020/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  //#region Orders

  let ordersStore: { value: Order[]};
  const getOrdersData =  async () => {
    if (!ordersStore) {
      const response = await fetch('https://services.odata.org/V3/Northwind/Northwind.svc/Orders?$format=json');
      ordersStore = await response.json();
    }
    return ordersStore;
  };

  server.get('/api/orders', async (req, res) => {
    const data = await getOrdersData();
    res.json(data);
  });

  server.get('/api/orders/:id', async (req, res) => {
    const data = await getOrdersData();
    const id = parseInt(req.params.id, 10);
    const order = data.value.find(x => x.OrderID === id);

    if (!order) {
      return res.status(404);
    }
    res.json(order);
  });

  server.post('/api/orders', express.json(), async (req, res) => {
    const data = await getOrdersData();
    const order: Order = req.body;

    order.OrderID = data.value.length + 1;
    data.value.push(order);
    res.status(201).json(order);
  });

  server.put('/api/orders', express.json(), async (req, res) => {
    const data = await getOrdersData();
    const updatedOrder: Order = req.body;
    const order = data.value.find(x => x.OrderID === updatedOrder.OrderID);

    if (!order) {
      // TODO: Create 201
      return res.status(404).end();
    }
    Object.assign(order, updatedOrder);
    res.status(204).end();
  });

  server.delete('/api/orders/:id', async (req, res) => {
    const data = await getOrdersData();
    const id = parseInt(req.params.id, 10);
    const index = data.value.findIndex(x => x.OrderID === id);

    if (index === -1) {
      return res.status(404).end();
    }
    data.value.splice(index, 1);
    return res.status(204).end();
  });

  //#endregion Orders

  //#region Companies
  let companyStore: { value: Customer[] };
  const companyStockStore: { value: {}[] } = { value: [] };

  const getCustomersData =  async () => {
    if (!companyStore) {
      const response = await fetch('https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json');
      companyStore = await response.json();
    }
    return companyStore;
  };

  server.get('/api/companies', async (req, res) => {
    const companies = await getCustomersData();
    res.json(companies);
  });

  server.get('/api/companies/stock', async (req, res) => {
    if (!companyStockStore.value.length) {
      const companies = await getCustomersData();
      const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      companies.value.forEach(c => {
        companyStockStore.value.push(
          months.map(month => ({ month, companyId: c.CustomerID, [c.CompanyName]: faker.random.number({min: 50, max: 150}) }))
        );
      });
    }
    res.json(companyStockStore);
  });
  //#endregion Companies

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}