Closed
Description
I'm using the angular 2 universal cli
If i send the http.get request through the service, it is requesting the api twice
##package.json
{ "name": "test-app", "version": "0.0.0", "license": "MIT", "angular-cli": {}, "scripts": { "start": "ung serve", "lint": "tslint \"src/**/*.ts\"", "test": "ung test", "pree2e": "webdriver-manager update --standalone false --gecko false", "e2e": "protractor" }, "private": true, "dependencies": { "@angular/animations": "^5.0.1", "@angular/common": "2.2.3", "@angular/compiler": "2.2.3", "@angular/core": "2.2.3", "@angular/forms": "2.2.3", "@angular/http": "2.2.3", "@angular/platform-browser": "2.2.3", "@angular/platform-browser-dynamic": "2.2.3", "@angular/platform-server": "^2.2.3", "@angular/router": "3.2.3", "@ngx-universal/state-transfer": "^4.0.1", "angular2-express-engine": "2.1.0-rc.1", "angular2-flash-messages": "^1.0.8", "angular2-jwt": "^0.2.3", "angular2-platform-node": "2.1.0-rc.1", "angular2-universal": "2.1.0-rc.1", "angular2-universal-polyfills": "2.1.0-rc.1", "bcryptjs": "^2.4.3", "bootstrap": "^3.3.7", "compression": "1.6.2", "core-js": "^2.4.1", "cors": "^2.8.4", "express": "^4.14.0", "font-awesome": "^4.7.0", "jquery": "^3.2.1", "jsonwebtoken": "^8.1.0", "mongoose": "^4.13.1", "passport": "^0.4.0", "passport-jwt": "^3.0.0", "passport-local": "^1.0.0", "rxjs": "5.0.0-beta.12", "ts-helpers": "^1.1.1", "zone.js": "^0.6.23" }, "devDependencies": { "@angular/compiler-cli": "2.2.3", "@types/jasmine": "2.5.38", "@types/node": "^6.0.42", "@types/body-parser": "0.0.29", "@types/compression": "0.0.29", "@types/cookie-parser": "^1.3.29", "@types/express": "^4.0.29", "@types/express-serve-static-core": "^4.0.29", "@types/mime": "0.0.28", "@types/serve-static": "^1.7.27", "universal-cli": "1.0.0-alpha.universal.3", "codelyzer": "~2.0.0-beta.1", "jasmine-core": "2.5.2", "jasmine-spec-reporter": "2.5.0", "karma": "1.2.0", "karma-chrome-launcher": "^2.0.0", "karma-cli": "^1.0.1", "karma-jasmine": "^1.0.2", "karma-remap-istanbul": "^0.2.1", "protractor": "~4.0.13", "ts-node": "1.2.1", "tslint": "^4.0.2", "typescript": "~2.0.3" } }
server.ts
/**
* the polyfills must be the first thing imported
*/
import './polyfills.ts';
import './__2.1.1.workaround.ts'; // temporary until 2.1.1 things are patched in Core
import * as path from 'path';
import * as express from 'express';
import * as compression from 'compression';
import { createEngine } from 'angular2-express-engine';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app/app.node.module';
import { environment } from './environments/environment';
import { routes } from './server.routes';
// App
const app = express();
const ROOT = path.join(path.resolve(__dirname, '..'));
const port = process.env.PORT || 4200;
/**
* enable prod mode for production environments
*/
if (environment.production) {
enableProdMode();
}
/**
* Express View
*/
app.engine('.html', createEngine({}));
app.set('views', path.join(ROOT, 'client'));
app.set('view engine', 'html');
/**
* Enable compression
*/
app.use(compression());
/**
* serve static files
*/
app.use('/', express.static(path.join(ROOT, 'client'), {index: false}));
/**
* place your api routes here
*/
// app.use('/api', api);
/**
* bootstrap universal app
* @param req
* @param res
*/
function ngApp(req: any, res: any) {
res.render('index', {
req,
res,
ngModule: AppModule,
preboot: false,
baseUrl: '/',
requestUrl: req.originalUrl,
originUrl: req.hostname
});
}
/**
* use universal for specific routes
*/
app.get('/', ngApp);
app.use('/api', require('./routes/api'));
routes.forEach(route => {
app.get(`/${route}`, ngApp);
app.get(`/${route}/*`, ngApp);
});
/**
* if you want to use universal for all routes, you can use the '*' wildcard
*/
app.get('*', function (req: any, res: any) {
res.setHeader('Content-Type', 'application/json');
const pojo = {status: 404, message: 'No Content'};
const json = JSON.stringify(pojo, null, 2);
res.status(404).send(json);
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
api.ts
let express = require('express');
let router = express.Router();
let siteInfo = { name: "ABC", msg: 'Get Info'};
router.get('/', function(req, res, next) {
console.log("In API")
res.send(siteInfo)
});
module.exports = router;
app.component.html
<h1>
{{title}}
</h1>
<app-home></app-home>
home.component.ts
import { Component, OnInit } from '@angular/core';
import { GetinfoService } from '../getinfo.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [GetinfoService]
})
export class HomeComponent implements OnInit {
constructor(
private getInfo: GetinfoService
) { }
ngOnInit() {
this.getInfo.getInformation()
.subscribe(
(info) => {
console.log(info)
},
(err) => {
console.log(err)
}
);
}
}
getinfo.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Observable } from "rxjs/Observable";
@Injectable()
export class GetinfoService {
apiUrl = 'http://localhost:4200/';
headers: Headers = new Headers({'Content-Type': 'application/json'})
constructor(private http : Http) { }
getInformation():Observable {
let url = this.apiUrl +'api';
return this.http.get(url, {headers: this.headers}).map(res => res.json());
}
}
in the console api is calling the twice why
webpack: bundle is now VALID
Listening on port 4200
Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
In API
{ name: 'ABC', msg: 'Get Info' }
In API
Here the API is called again so I have Used to configure the BrowserModule on app.browser.module.ts file.
##app.broswer.module.ts
/** * This file and `main.node.ts` are identical, at the moment(!) * By splitting these, you're able to create logic, imports, etc that are "Platform" specific. * If you want your code to be completely Universal and don't need that * You can also just have 1 file, that is imported into both * client.ts and server.ts */ import { NgModule } from '@angular/core'; import { UniversalModule } from 'angular2-universal'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './index'; import { HomeComponent } from './home/home.component'; // import { RouterModule } from '@angular/router'; // import { appRoutes } from './app/app.routing'; /** * Top-level NgModule "container" */ @NgModule({ /** Root App Component */ bootstrap: [ AppComponent ], /** Our Components */ declarations: [ AppComponent, HomeComponent ], imports: [ /** * NOTE: Needs to be your first import (!) * BrowserModule, HttpModule, and JsonpModule are included */ BrowserModule.withServerTransition({ appId: 'test-app' }), UniversalModule, FormsModule /** * using routes */ // RouterModule.forRoot(appRoutes) ] }) export class AppModule { }
Am geeting the below error
Uncaught Error: Module build failed: Error: E:/projects/Angular2/test-app/src/app/app.browser.module.ts (32,19): Property 'withServerTransition' does not exist on type 'typeof BrowserModule'.) at _checkDiagnostics (E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:115:15) at E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:140:17 at at _checkDiagnostics (E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:115:15) at E:\projects\Angular2\test-app\node_modules\@ngtools\webpack\src\loader.js:140:17 at at Object.433 (http://localhost:4200/client.bundle.js:83:7) at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30) at Object.334 (http://localhost:4200/client.bundle.js:29:82) at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30) at Object.624 (http://localhost:4200/client.bundle.js:171:18) at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30) at webpackJsonpCallback (http://localhost:4200/inline.bundle.js:24:23) at http://localhost:4200/client.bundle.js:1:1
Metadata
Metadata
Assignees
Labels
No labels