{{(countValue/60) %60 | number:'2.0-0'}}
is there is a way to round down, the above code will give the result for "0.9" is "1" I want 0 can anyone help me
For this either you can just use
Math.floor(yourValue);
or if you wanted to use custom pipes., pls refer the code below
// round.pipe.ts
import {Pipe, PipeTransform} from "#angular/core";
#Pipe({name: 'round'})
export class RoundPipe implements PipeTransform {
/**
*
* #param value
* #returns {number}
*/
transform(value: number): number {
return Math.floor(value);
}
}
Import it in your module
// app.module.ts
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing
],
declarations: [
AppComponent,
RoundPipe
],
providers: [
BaseRequestOptions
],
bootstrap: [AppComponent]
})
And in your html,
<!--your html -->
<span>{{(countValue/60) %60 | round }}</span>
Related
I scatered the web for this answer or something similar but with no avail. I did found something that may help explain what am I looking for.
I want to get multiple Mongo connection in a Nestjs project based on a payload received from a RabbitMQ broker. Is there a way to do this in a similar way like in this post with the interception of the request in the declaration of the MongooseModule?
#Module( {
imports: [ RabbitMQModule.forRootAsync( RabbitMQModule, {
imports: [ ConfigModule ],
useClass: AmqpConfig,
inject: [ ConfigService ],
} ) ],
controllers: [ MessagingController ],
providers: [ MessagingService, ConfigService ],
exports: [ MessagingService, RabbitMQModule ]
} )
export class MessagingModule { }
The AmqpConfig class
#Injectable()
export class RabbitConfig {
constructor (
private readonly config: ConfigService,
) { }
createModuleConfig (): RabbitMQConfig | Promise<RabbitMQConfig> {
return {
name: this.name,
uri: this.uri,
exchanges: this.exchanges,
connectionInitOptions: this.connectionInitOptions,
enableControllerDiscovery: true,
};
}
get uri (): string {
const { host, port } = this.config.get( 'amqp' );
return `${ host }:${ port || 5672 }`;
}
get name (): string {
return this.config.get( 'amqp' ).name;
}
get exchanges (): Array<RabbitMQExchangeConfig> {
return Object.values( this.config.get( 'amqp' ).exchanges ) as Array<RabbitMQExchangeConfig>;
}
get connectionInitOptions () {
return this.config.get( 'amqp' ).connectionInitOptions;
}
};
How exactly should I configure the MongooseModule?
#Module( {
imports: [
ConfigModule.forRoot( {
isGlobal: true,
load: [ envConfig ]
} ),
MongooseModule.forRootAsync( {
useClass: MongoConfig,
inject: [ ConfigService ]
} )
],
controllers: [ AppController ],
providers: [ AppService ],
} )
export class AppModule { }
MongoConfig class:
export class MongoConfig implements MongooseOptionsFactory {
constructor ( private readonly config: ConfigService ) { }
createMongooseOptions (): MongooseModuleOptions | Promise<MongooseModuleOptions> {
return {
uri: this.uri
};
}
get uri () {
return this.config.get( 'mongo' ).uri;
}
}
I am trying with following rollup.config.js file
import typescript from "rollup-plugin-typescript2";
import pkg from "./package.json";
import copy from 'rollup-plugin-copy'
import clean from 'rollup-plugin-clean';
export default [
{
input: "src/index.ts",
external: Object.keys(pkg.peerDependencies || {}),
watch: {
skipWrite: false,
clearScreen: false,
include: 'src/**/*',
//exclude: 'node_modules/**',
// chokidar: {
// paths: 'src/**/*',
// usePolling: false
// }
},
plugins: [
clean(),
copy({
targets: [
{ src: 'src/*', dest: 'dist' }
]
}),
typescript({
typescript: require("typescript"),
include: [ "*.ts+(|x)", "**/*.ts+(|x)", "*.d.ts", "**/*.d.ts" ]
}),
],
output: [
{ file: pkg.main, format: "cjs" },
{ file: pkg.module, format: "esm" },
{
file: "example/src/reactComponentLib/index.js",
format: "es",
banner: "/* eslint-disable */"
}
]
}
];
I want to rebuild when anything in src changes. I have couple of files which are not imported in .js and .ts files but I want them to copy in dist folder. copy is working fine but the watch is not picking up changes in those other files. Tried alot of variations on chokidar options but no luck yet.
Anyone have any idea how to resolve this?
watch.include only works on files pertaining to the module graph so if they are not imported they won't be included (https://rollupjs.org/guide/en/#watchinclude).
You can solve this by creating a small plugin that calls this.addWatchFile on those external files when the build starts. Here is an example:
plugins: [
{
name: 'watch-external',
buildStart(){
this.addWatchFile(path.resolve(__dirname, 'foo.js'))
}
}
]
Combine it with some globbing utility such as fast-glob and just call this.addWatchFile for every file you want to copy:
import fg from 'fast-glob';
export default {
// ...
plugins: [
{
name: 'watch-external',
async buildStart(){
const files = await fg('src/**/*');
for(let file of files){
this.addWatchFile(file);
}
}
}
]
}
Config
// ./docs/.vuepress/config.js
module.exports = {
...
chainWebpack: (config, isServer) => {
config.module
.rule("js") // Find the rule.
.use("babel-loader") // Find the loader
.tap(options =>
merge(options, {
presets: [
["#babel/preset-env"],
["#vue/babel-preset-jsx", { injectH: false }]
],
plugins: [
[
"import",
{
libraryName: "ant-design-vue",
libraryDirectory: "es",
style: "css"
}
],
"#babel/plugin-proposal-optional-chaining"
]
})
);
}
}
The config didn't work, when I ran the code I met the following error.
Error
Uncaught Error: Module parse failed: Unexpected token (87:11)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| },
| render(h) {
return <a-tree></a-tree>;
| }
| };
Could someone give me the right config?
I believe this is a setup bug, but I don't know what to do anymore, I tried a lot of stuff. We have an app setup and tests are failing with error:
src/__tests__/App.spec.tsx
● Test suite failed to run
SyntaxError: .../react-native/Libraries/Storage/AsyncStorage.js: Unexpected token, expected "," (31:19)
29 | */
30 | const AsyncStorage = {
> 31 | _getRequests: ([]: Array<any>),
| ^
32 | _getKeys: ([]: Array<string>),
33 | _immediate: (null: ?number),
34 |
at Parser.raise (node_modules/#babel/core/node_modules/babylon/lib/index.js:776:15)
at Parser.unexpected (node_modules/#babel/core/node_modules/babylon/lib/index.js:2079:16)
at Parser.expect (node_modules/#babel/core/node_modules/babylon/lib/index.js:2067:28)
at Parser.parseParenAndDistinguishExpression (node_modules/#babel/core/node_modules/babylon/lib/index.js:3283:14)
at Parser.parseExprAtom (node_modules/#babel/core/node_modules/babylon/lib/index.js:3113:21)
at Parser.parseExprSubscripts (node_modules/#babel/core/node_modules/babylon/lib/index.js:2757:21)
at Parser.parseMaybeUnary (node_modules/#babel/core/node_modules/babylon/lib/index.js:2736:21)
at Parser.parseExprOps (node_modules/#babel/core/node_modules/babylon/lib/index.js:2643:21)
at Parser.parseMaybeConditional (node_modules/#babel/core/node_modules/babylon/lib/index.js:2615:21)
at Parser.parseMaybeAssign (node_modules/#babel/core/node_modules/babylon/lib/index.js:2562:21)
This is the App.spec.tsx code:
import React from 'react';
import renderer from 'react-test-renderer';
import { App } from '../app';
it('renders correctly with defaults', () => {
const app = renderer.create(<App />).toJSON();
expect(app).toMatchSnapshot();
});
My jest.json:
{
"preset": "react-native",
"cacheDirectory": ".jest/cache",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
"\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation)"
],
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/",
"<rootDir>/lib/",
"./build"
],
"globals": {
"window": true
}
}
Is there any helpful information that I can provide? Is this an issue with flow-types, babel...? My .babelrc is really simple.
I am not able to import images in my headercomponent.ts.
I suspect it is because of something i am doing wrong while compiling ts(using webpack ts loader) because same thing works with react( where the components are written in es6)
The error location is
//headercomponent.ts
import {Component, View} from "angular2/core";
import {ROUTER_DIRECTIVES, Router} from "angular2/router";
import {AuthService} from "../../services/auth/auth.service";
import logoSource from "../../images/logo.png"; //**THIS CAUSES ERROR** Cannot find module '../../images/logo.png'
#Component({
selector: 'my-header',
//templateUrl:'components/header/header.tmpl.html' ,
template: `<header class="main-header">
<div class="top-bar">
<div class="top-bar-title">
<img src="{{logoSource}}">
</div>
my webpack config is
// webpack.config.js
'use strict';
var path = require('path');
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var basePath = path.join(__dirname,'public');
//const TARGET = process.env.npm_lifecycle_event;
console.log("bp " + basePath)
module.exports = {
entry: path.join(basePath,'/components/boot/boot.ts'),
output: {
path: path.join(basePath,"..","/build"), // This is where images AND js will go
publicPath: path.join(basePath,"..","/build/assets"),
// publicPath: path.join(basePath ,'/images'), // This is used to generate URLs to e.g. images
filename: 'bundle.js'
},
plugins: [
new ExtractTextPlugin("bundle.css")
],
module: {
preLoaders: [ { test: /\.tsx$/, loader: "tslint" } ],
//
loaders: [
{ test: /\.(png!jpg)$/, loader: 'file-loader?name=/img/[name].[ext]' }, // inline base64 for <=8k images, direct URLs for the rest
{
test: /\.json/,
loader: 'json-loader',
},
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: [/node_modules/]
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.scss$/,
exclude: [/node_modules/],
loader: ExtractTextPlugin.extract("style", "css!postcss!sass?outputStyle=expanded")
},
// fonts and svg
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml" }
]
},
resolve: {
// now require('file') instead of require('file.coffee')
extensions: ['', '.ts', '.webpack.js', '.web.js', '.js', '.json', 'es6', 'png']
},
devtool: 'source-map'
};
and my directory structure looks like this
-/
-server/
-build/
-node-modules/
-public/
-components/
-boot/
-boot.component.ts
-header/
-header.component.ts
-images/
-logo.png
-services/
-typings/
-browser/
-main/
-browser.d.ts
-main.d.ts
-tsconfig.json
-typings.json
my tsconfig file is as follows:
//tsconfig.json
{
"compilerOptions": {
"target": "es5",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
I suspect I am messing some thing in typescript compilation , not sure what
The problem is that you confuse TypeScript level modules and Webpack level modules.
In Webpack any file that you import goes through some build pipeline.
In Typescript only .ts and .js files are relevant and if you try to import x from file.png TypeScript just does not know what to do with it, Webpack config is not used by TypeScript.
In your case you need to separate the concerns, use import from for TypeScript/EcmaScript code and use require for Webpack specifics.
You would need to make TypeScript ignore this special Webpack require syntax with a definition like this in a .d.ts file:
declare function require(string): string;
This will make TypeScript ignore the require statements and Webpack will be able to process it in the build pipeline.
Instead of:
import image from 'pathToImage/image.extension';
Use:
const image = require('pathToImage/image.extension');
I'm using
import * as myImage from 'path/of/my/image.png';
and created a typescript definition with
declare module "*.png" {
const value: any;
export = value;
}
This only works when you have a correct handler like the file-loader in webpack. Because this handler will give you a path to your file.
A small improvement to Christian Stornowski's answer would be to make the export default, i.e.
declare module "*.png" {
const value: string;
export default value;
}
So you can import an image using:
import myImg from 'img/myImg.png';
I also had same issue so I used following approach:
import * as myImage from 'path/of/my/image';
In my component I simply assigned the imported image to a data member;
export class TempComponent{
public tempImage = myImage;
}
and used it in template as:
<img [src]="tempImage" alt="blah blah blah">
If you want to use the ES6 syntax for importing.
First be sure that in your tsconfig.json you have:
target: 'es5',
module: 'es6'
The following should now work:
import MyImage from './images/my-image.png';
To be able to use default import like this:
import grumpyCat from '../assets/grumpy_cat.jpg';
Define jpg module declaration:
declare module "*.jpg" {
const value: string;
export default value;
}
and in your tsconfig use "module": "es6" (see #vedran comment above) or when you use "module": "commonjs" add "esModuleInterop": true,
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"esModuleInterop": true,
...
Source: https://github.com/TypeStrong/ts-loader/issues/344#issuecomment-381398818