New to Angular/ts/js. I went through the Tour of Heroes tutorial, now I am trying to incorporate compiling and building via gulp. Seems to be going well enough but I can't seem to figure this roadblock out.
In a single example, I have the app/components/app.module.ts file (disregard the deep relative import pathing; I plan on refactoring it later):
import { BrowserModule } from '../../node_modules/#angular/platform-browser';
import { NgModule } from '../../node_modules/#angular/core';
import { FormsModule } from '../../node_modules/#angular/forms';
import { HttpModule } from '../../node_modules/#angular/http';
import { InMemoryWebApiModule } from '../../node_modules/angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HeroService } from './hero.service';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroSearchComponent } from './hero-search.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService, { delay: 600 })
],
declarations: [
AppComponent,
DashboardComponent,
HeroSearchComponent,
HeroesComponent,
HeroDetailComponent,
],
providers: [HeroService],
bootstrap: [AppComponent]
})
export class AppModule { }
After I compile it to js and serve up the application, the console tells me:
"Cannot GET /js/components/app.component"
(along with all the other modules after it), even though that js DOES exist at the location.
I believe I found that it's still expecting it to be the ts file. If I explicitly change the import to be a js file as
"import { AppComponent } from './app.component.js';"
then it loads fine.
In my research, I think I may need a sourcemap, but being entirely green at this I'm not sure. I'm not entirely sure how to describe/define the issue so web searches haven't netted me anything definitive. Can someone get me on the right track?
Update
Here is my gulpfile. Still learning so I know it's messy.
// grab our packages
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
clean = require('gulp-clean'),
connect = require('gulp-connect'),
gnf = require('gulp-npm-files');
const tscConfig = require('./tsconfig.json');
var ts = require('gulp-typescript');
var merge = require('merge2');
// define the default task and add the watch task to it
gulp.task('default', ['watch']);
// configure the jshint task
gulp.task('jshint', function() {
return gulp.src('app/components/js/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
gulp.watch('app/components/js/**/*.js', ['jshint']);
});
gulp.task('compileTs', function () {
var tsResult = gulp.src('app/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('dist/definitions')),
tsResult.js.pipe(gulp.dest('dist/js'))
]);
});
gulp.task('compileEnviroTs', function () {
var tsResult = gulp.src('environments/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('dist/definitions')),
tsResult.js.pipe(gulp.dest('dist/environments'))
]);
});
gulp.task('cleanDist', function() {
return gulp.src('dist', {read: false})
.pipe(clean());
});
gulp.task('copyDeps', ['cleanDist'], function() {
gulp
.src(gnf(null, './package.json'), {base:'./'})
.pipe(gulp.dest('dist'));
});
gulp.task('copyEnvironments', ['copyDeps'], function() {
return gulp.src('environments/**/*')
.pipe(gulp.dest('dist/environments'));
});
gulp.task('copyComponents', ['copyEnvironments'], function() {
return gulp.src('app/components/**/*')
.pipe(gulp.dest('dist/components'));
});
gulp.task('copyCss', ['copyComponents'], function() {
return gulp.src('app/css/**/*')
.pipe(gulp.dest('dist/css'));
});
gulp.task('copyImg', ['copyCss'], function() {
return gulp.src('app/img/**/*')
.pipe(gulp.dest('dist/img'));
});
gulp.task('copyJs', ['copyImg'], function() {
return gulp.src('app/js/**/*')
.pipe(gulp.dest('dist/js'));
});
gulp.task('copyPartials', ['copyJs'], function() {
return gulp.src('app/partials/**/*')
.pipe(gulp.dest('dist/partials'));
});
gulp.task('copyFiles', ['copyPartials'], function() {
return gulp.src('app/**/*')
.pipe(gulp.dest('dist'));
});
gulp.task('connect', ['copyFiles', 'compileTs'], function () {
connect.server({
root: 'dist/',
port: 8888
});
});
gulp.task('dev', ['cleanDist', 'compileTs', 'compileEnviroTs', 'copyDeps', 'copyFiles', 'connect']);
Update
Here is my code repo, if it helps any. I'm in the gulp branch.
https://github.com/fmjnax/LearningAngular.git
Related
I'm learning nest.js and I have an issue I may not completely understand.
In our company we have dev-gateway which checks MY_URL/.well-known/apollo/server-health endpoint to be sure services are up before creating and then download schema from MY_URL. MY_URL is variable we pass to configuration.
So I need to have GET http://MY_URL/.well-known/apollo/server-health to return { status: pass } and POST http://MY_URL/ to return schema/be graphql endpoint.
If path in GraphQLFederationModule config is equal to / it works, but if I have path defined as /graphql then:
GET http://MY_URL/.well-known/apollo/server-health returns { status: pass } and I think it's issue, I wanted graphql service under /graphql path
GET http://MY_URL/graphql/.well-known/apollo/server-health is graphql endpoint and it return error (lack of query) and I think it should return { status: pass }
GET http://MY_URL/graphql returns graphql enpoint which is OK
I prepared some minimal working version and I'm using:
"#apollo/federation": "^0.25.1",
"#nestjs/common": "^7.6.15",
"#nestjs/core": "^7.6.15",
"#nestjs/graphql": "^7.10.3",
"apollo-server-express": "^2.22.2",
"graphql": "^15.5.0",
"graphql-tools": "^7.0.4",
import { NestFactory } from '#nestjs/core';
import { Module } from '#nestjs/common';
import {
GraphQLFederationModule,
Query,
Resolver,
ResolveReference,
Directive, Field, ID, ObjectType
} from '#nestjs/graphql';
import { Controller, Get } from '#nestjs/common';
#Controller('')
export class AppController {
#Get()
healthCheck() {
return 'Hello World!';
}
}
#ObjectType()
#Directive('#key(fields: "_id")')
export class AdSpot {
#Field((type) => ID)
_id: string;
#Field((type) => String)
name: string
}
#Resolver((of) => AdSpot)
export class CatResolver {
#Query((returns) => [AdSpot], { name: 'adSpots' })
async getAdSpots() {
return [];
}
}
#Module({
providers: [CatResolver],
})
export class CatsModule {}
#Module({
imports: [
CatsModule,
GraphQLFederationModule.forRoot({
include: [CatsModule],
path: '/graphql',
autoSchemaFile: true,
sortSchema: true,
playground: true,
disableHealthCheck: false,
}),
],
controllers: [AppController],
})
export class AppModule {}
async function bootstrap() {
try {
const app = await NestFactory.create(AppModule);
await app.listen(3010);
} catch (err) {
console.log('-------------------------------------');
console.log(err);
}
}
bootstrap();
What am I doing wrong? Did I miss some configuration or is it a bug?
Use the relative path i.e
typePaths: ['**/*.graphql'],
In Your case
#Module({
imports: [
CatsModule,
GraphQLFederationModule.forRoot({
include: [CatsModule],
typePaths: ['**/*.graphql'],
autoSchemaFile: true,
sortSchema: true,
playground: true,
disableHealthCheck: false,
}),
],
controllers: [AppController],
})
I need to use publish Subscribe methods in my Ionic 3 application.
I followed this page.
Is there any way we can link MQTT with our Ionic 3 application? If yes, how so?
How exactly do I need to go about it for a successful connection?
I installed ng2-mqtt service using
npm install ng2-mqtt --save
This is my code:
index.html
<script src="cordova.js"></script>
<script src="node_modules/ng2-mqtt/mqttws31.js" type="text/javascript"></script>
home.ts
import {Paho} from 'mqttws31'
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private _client: Paho.MQTT.Client;
constructor(public paho: Paho) {
}
this._client = new Paho.MQTT.Client("52.66.30.178", 1883, "path", "someclient_id");
this._client.onConnectionLost = (responseObject: Object) => {
console.log('Connection lost.');
this.getServerMessage();
this._client.onMessageArrived = (message: Paho.MQTT.Message) => {
console.log('Message arrived.');
};
this._client.connect({ onSuccess: this.onConnected.bind(this); });
}
Still I can't get it to work.
Any suggestions and changes will help me. I'm stuck please do.
After searching and trying out different things for a while, I found this solution, you can use this library if you want to use MQTT in your project.
Install it using npm install ngx-mqtt --save
Usage: app.module.ts
import { Observable } from 'rxjs/Observable';
import {
IMqttMessage,
MqttModule,
MqttService
} from 'ngx-mqtt';
export const MQTT_SERVICE_OPTIONS = {
hostname: '13.127.53.13',
port: 9001,
path: '/mqtt'
};
export function mqttServiceFactory() {
return new MqttService(MQTT_SERVICE_OPTIONS);
}
#NgModule({
imports: [
BrowserModule,
HttpModule,
MqttModule.forRoot({
provide: MqttService,
useFactory: mqttServiceFactory
}),
IonicModule.forRoot(MyApp)
]
And then you can use it in your page like: (ex: home.ts file)
import { IMqttMessage, MqttModule, MqttService } from 'ngx-mqtt';
import { Observable } from 'rxjs/Observable';
export class HomePage {
constructor( private _mqttService: MqttService)
{
this._mqttService.observe('home/door').subscribe((message: MqttMessage) =>
{
this.sensor1 = message.payload.toString();
console.log(this.sensor1);
});
}
publishMessage()
{
this._mqttService.unsafePublish("home/button", "on", {qos: 0, retain: false});
}
For more information about this library: https://github.com/sclausen/ngx-mqtt
after converting a simple react module to es6 class; i got some gulp parsing errors.
var React = require('react');
// import React from 'react';
class UdpComp extends React.Component {
constructor (props){
super(props);
this.state = { udpinput: props.udpinput };
},
render: function() {
return(
<div className="udpText">
<h2>UDP-INPUT: {this.state.udpinput}</h2>
</div>
) // return
} // render
})// UdpComp
export default UdpComp;
ok, my gulpfile.babel.js looks like this:
var gulp = require('gulp'),
browserify = require('gulp-browserify'),
concatCss = require('gulp-concat-css'),
sass = require('gulp-sass'),
run = require('gulp-run');
var src = './process',
app = './app';
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded'
}; // https://www.sitepoint.com/simple-gulpy-workflow-sass/
gulp.task('js', function() {
return gulp.src( src + '/js/apprender.js' )
.pipe(browserify({
transform: 'reactify',
extensions: 'browserify-css',
debug: true
}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(gulp.dest(app + '/js'));
});
gulp.task('html', function() {
gulp.src( src + '/**/*.html');
});
gulp.task('css', function() {
gulp.src( src + '/css/*.css')
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(concatCss('app.css'))
.pipe(gulp.dest(app + '/css'));
});
gulp.task('fonts', function() {
gulp.src('node_modules/bootstrap/dist/fonts/**/*')
.pipe(gulp.dest(app + '/fonts'));
});
gulp.task('watch', ['serve'], function() {
gulp.watch( src + '/js/**/*', ['js']);
gulp.watch( src + '/css/**/*.css', ['css']);
gulp.watch([ app + '/**/*.html'], ['html']);
});
gulp.task('serve', ['html', 'js', 'css'], function() {
run('electron app/main.js').exec();
});
gulp.task('default', ['watch', 'fonts', 'serve']);
when calling gulp I get
\process\js\UdpCompReact.js: Parse Error: Line 14: Unexpected
identifier error
why, how can I parse es6 code?
Can't see what's on line 14 but I'd guess it's the comma right after your constructor. As opposed to ES5 "classes", ES6 classes don't require (and don't allow) commas between methods. Just remove it and it should work (or at least get past line 14)
You need a transpiler that converts it to ES5, afterwards pipe it in the gulp task. I use babel and there is a gulp-babel npm package
I changed my code to this, when using the older version the transpiling works.
import React from 'react' throws an error.
// var React = require('react');
import React from 'react';
class UdpComp extends React.Component {
constructor (props){
super(props);
this.state = { udpinput: this.props.udpinput };
}
render () {
return(
<div className="udpText">
<h2>UDP-INPUT: {this.state.udpinput}</h2>
</div>
) // return
} // render
}; // UdpComp
module.exports = UdpComp;
// export default UdpComp;
I can set the duration of a snackbar message like so
let config = new MdSnackBarConfig();
config.duration = 5000;
this.snackBar.open(element.text, 'OK', config);
However I need to set the duration for multiple snackbars and would rather not have to pass in the config each time.
Can I somehow set a global duration config?
Thanks!
I know this post is from a few years ago but for future reference i'm going to answer this anyway. Hoping I help someone who comes across this post like I did.
You can now inject the MatSnackBar with default options for modules by using the providers in your #NgModule:
import { MatSnackBarModule, MAT_SNACK_BAR_DEFAULT_OPTIONS } from '#angular/material';
#NgModule({
declarations: [],
imports: [
MatSnackBarModule
],
exports: [
MatSnackBarModule
],
providers: [
{ provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 2500 } }
]
})
Source: Material Angular doc's
What we've done is included an external app.config.ts file at the module level and include it where we need it. This is an example of what's in the file.
export class Config {
static apiUrl = "api/";
static token = "";
static snackBarDurration = 5000;
......
}
Then, all you have to do is declare it in your module and then import it in the component or service in which you want to use it. Here is an example.
import { Injectable } from "#angular/core";
import { Config } from "../../app.config";
#Injectable()
export class SnackBarService {
.... // declare your snackbar here
constructor() { }
showSnackBar(elementText: string){
let config = new MdSnackBarConfig();
config.duration = Config.snackBarDurration; // Here is your change
this.snackBar.open(elementText, 'OK', config);
}
}
I know it's not solution for a global configuration, but to
make invocation more compact I declared config in params:
this.snackBar.open(elementText, 'OK', { duration: 3000 });
I've set up an app with react using react-router for routing and are having issues bundling it all.
I'm trying to build/bundle all the js files using gulp-requirejs. But somehow the shim is not included, or the react-router is just ignored. Whatever the problem is, I just end up with an error in the browser console saying Uncaught Error: app missing react-router
I'm including the most important code, feel free to ask if something doesn't make sense.
gulpfile.js
Almond.js is there to replace requirejs
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
rjs = require('gulp-requirejs'),
gulp.task('requirejsBuild', function() {
rjs({
baseUrl: './app/resources/js/',
out: 'app.min.js',
paths: {
'react': '../bower_components/react/react-with-addons',
'react-router': '../bower_components/react-router/dist/react-router',
'react-shim': 'react-shim',
'jquery': '../bower_components/jquery/dist/jquery'
},
shim: {
'react-shim': {
exports: 'React'
},
'react-router': {
deps: ['react-shim']
}
},
deps: ['jquery', 'react-router'],
include: ['init'],
name: '../bower_components/almond/almond'
})
.pipe(uglify()).pipe(gulp.dest('./app/resources/js/'));
});
init.js
require.config({
baseUrl: '/resources/js/',
deps: ['jquery'],
paths: {
'react': '../bower_components/react/react-with-addons',
'react-router': '../bower_components/react-router/dist/react-router',
'react-shim': 'react-shim',
'jquery': '../bower_components/jquery/dist/jquery'
},
shim: {
'react-shim': {
exports: 'React'
},
'react-router': {
deps: ['react-shim']
}
}
});
require(['react', 'app'], function(React, App) {
var app = new App();
app.init();
});
app.js
define([
'react',
'react-router',
], function(
React,
Router,
){
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var DefaultRoute = Router.DefaultRoute;
/**
* Wrapper for it all
*
* #type {*|Function}
*/
var Wrapper = React.createClass({displayName: "Wrapper",
mixins: [Router.State],
render: function() {
return (
React.createElement(RouteHandler, null)
);
}
});
var routes = (
React.createElement(Route, {handler: Wrapper, path: "/"}, null)
);
var App = function(){};
App.prototype.init = function () {
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(React.createElement(Handler, null), document.getElementById('content'));
});
};
return App;
}
);
index.html
Mainly containing a script tag
After build you have to manually swap the src with app.min.js
<script data-main="/resources/js/init" src="/resources/bower_components/requirejs/require.js"></script>