Posts

Showing posts with the label typescript

Can you generate sine wave data continuously from an Angular service and inject it into a component?

Image
Clash Royale CLAN TAG #URR8PPP Can you generate sine wave data continuously from an Angular service and inject it into a component? I have a component which has an injected service to retrieve static mock data. I would like to add the ability to generate data at a variable frequency and send the new (appended, time series) data to the component as it is generated. I can't for the life of me figure out how to accomplish this. All I know for sure is that the data object for the component must be immutable. plotter.component.ts: import { Component, OnInit } from '@angular/core'; import { MockDataService } from '../../services/mock-data/mock-data.service'; @Component({ selector: 'app-plotter', templateUrl: './plotter.component.html', styleUrls: ['./plotter.component.css'] }) export class PlotterComponent implements OnInit { single: any; multi: any; // rt needs to be an immutable object array // rt needs to be updated with data from ...

How do I run my CDK app?

Image
Clash Royale CLAN TAG #URR8PPP How do I run my CDK app? I created and built a new CDK project: mkdir myproj cd myproj cdk init --language typescript npm run build If I try to run the resulting javascript, I see the following: PS C:reposmyproj> node .binmyproj.js CloudExecutable/1.0 Usage: C:reposmyprojbinmyproj.js REQUEST REQUEST is a JSON-encoded request object. What is the right way to run my app? 2 Answers 2 You don't need to run your CDK programs directly, but rather use the CDK Toolkit instead. To synthesize an AWS CloudFormation from your app: cdk synth --app "node .binmyproj.js" To avoid re-typing the --app switch every time, you can setup a cdk.json file with: --app cdk.json { "app": "node .appmyproj.js" } You can also use the toolkit to deploy your app into an AWS environment: cdk deploy Or list all the stacks in your app: cdk ls The CDK application ...

What does “@” symbol mean in “import { Component } from '@angular/core';” statement?

Image
Clash Royale CLAN TAG #URR8PPP What does “@” symbol mean in “import { Component } from '@angular/core';” statement? I'm reading Angular 2 "5 Min Quickstart" and there is such a line: import { Component } from '@angular/core';" I can't figure out, what does @ symbol make in that import? TypeScript docs are also doesn't say anything about that. @ What does it mean? Possible duplicate of Understanding npm package @-prefix: @angular/router – Ankit Singh May 22 '16 at 9:57 your name sounds like Bill Gates :p – Ankush Jain Sep 3 '16 at 16:35 3 Answers 3 this is ju...

How to update component based on container's state change

Image
Clash Royale CLAN TAG #URR8PPP How to update component based on container's state change I have a React container called UserContainer which renders a component called UserComponent . UserContainer UserComponent The code looks approximately like this (I have removed the unnecessary bits): // **** CONTAINER **** // class UserContainer extends React.Component<ContainerProps, ContainerState> { state = { firstName: "placeholder" }; async componentDidMount() { const response = await this.props.callUserApi(); if (response.ok) { const content: ContainerState = await response.json(); this.setState({ firstName: content.firstName }); } } private isChanged(componentState: ComponentState) { return this.state.firstName === componentState.firstName; } async save(newValues: ComponentState) { if (!this.isChanged(newValues)) { console.log("No changes detected."); ...

Is it possible convert from *.js to *.ts by simply ading type definitions in the same file?

Image
Clash Royale CLAN TAG #URR8PPP Is it possible convert from *.js to *.ts by simply ading type definitions in the same file? Now, I have a code: const log = (m) => { console.log(m); return m; }; and want to convert to a valid *.ts code by simply adding a type definition line without touching the existing JavaScript lines, declare type log = (m: unknown) => unknown; const log = (m) => { //Error: [ts] Parameter 'm' console.log(m); //implicitly has an 'any' type. return m; // (parameter) m: any }; and got an Error: [ts] Parameter 'm' implicitly has an 'any' type. (parameter) m: any Is this inevitable? Is there any workaround? Please consider providing a concise response, a) Yes, there's a workaround, and the code is... b) No, there's no way, sure, it's inevitable because of ...REASON... c) I'm not sure the answer is a) or b), I don't know there's a workaround or not. So, I just want to comment . Obvi...

How can we make a verticle range silder in ionic?

Image
Clash Royale CLAN TAG #URR8PPP How can we make a verticle range silder in ionic? I have been trying to make a vertical range slider in ionic and tried to use ion-range. As it is good until it is horizontal but when we tried to make it verticle it does not work. I have tried to make it by HTML input tag it is working fine, but not able to apply any CSS classes. The code for HTML is as follows, <ion-content padding> <ion-scroll scrollY="true"> <div class="timeline"> <div class="cashback-date" [style.padding-top.px]="paddingTop+(sliderValue*50)"> {{date}} </div> <div class="range"> <!-- <div class="range-track" [style.height.px]="cashbackArray.length*50"></div> <div class="range-handle"></div> --> <input class="input-range" [style.height.px]="cashbackArray.length*50" type=...

filter typescript array based on another array

Image
Clash Royale CLAN TAG #URR8PPP filter typescript array based on another array There are several examples of this based on simple arrays, but I have 2 arrays of objects and cannot seem to get this to work. getAvailableApplications() : Application { var list; if (!this.userSettings) list = this.applications; else list = this.applications.filter(x=> this.userSettings.modules.filter(y=> x.entityId === y.moduleId )); return list; } This is always returning me the complete list of applications, and not removing ones that are not in the userSetting.modules array, despite the fact that I have an element in the userSettings.modules array. I also tried rewriting without lambdas, but it doesn't seem to recognise the module level userSettings variable this.applications.filter(function (x){ return this.userSettings.filter(function(y){ return x.entityId === y.moduleId; }) userSettings is declared as any, but is assigned a va...

Resolving typescript

Image
Clash Royale CLAN TAG #URR8PPP Resolving typescript How do I work with Firebase and my own Typescript interfaces? ie. I have a function here that I'm going to need the full Payment object, (not just the delta), so I get that via the DocumentReference object. Payment DocumentReference exports.resolveStripeCharge = functions.firestore.document('/payments/{paymentId}') .onWrite((change : Change <DocumentSnapshot>) => { change.after.ref.get().then((doc: DocumentSnapshot )=> { const payment : Payment = doc.data(); }) [ts] Type 'DocumentData' is not assignable to type 'Payment'. Property 'amount' is missing in type 'DocumentData'. const payment: Payment I get that the returned object wont necessarily conform the interface - but in anycase -what should I do here - if I want to enforce typing? Do I just use: const payment : Payment = <Payment>doc.data(); Or is there a much nicer solution? ...

TypeScript combining *.js + *.d.ts again?

Image
Clash Royale CLAN TAG #URR8PPP TypeScript combining *.js + *.d.ts again? TypeScript tsc -d "declaration" of "compilerOptions" generates corresponding '.d.ts' file. tsc -d For instance, from: const log = (m: unknown) => { console.log((m)); return m; }; it generates: const log = (m) => { console.log((m)); return m; }; and: declare const log: (m: unknown) => unknown; I think this is quite interesting because it "devides" the TypeScript source code to a native JavaScript code and the extra type definition. Then, here is my thought. After deviding the native code and type definition, is it easily possilbe to generate a valid TypeScript code by re-binding both codes. For instance: declare const log1: (m: unknown) => unknown; const log1 = m => { console.log((m)); return m; }; This code generates an errors: [ts] Cannot redeclare block-scoped variable 'log1'. for each statements. Why am I tring this? I'm m...

Create folder and Upload file to Google Drive from TypeScript cannot compile

Image
Clash Royale CLAN TAG #URR8PPP Create folder and Upload file to Google Drive from TypeScript cannot compile I'm trying to create a folder in Google Drive from node.js, I found an example here that also shows how to upload a file into the new folder. I use TypeScript and my code looks like this: getAuthorizedClient().then((client) => { const drive = new drive_v3.Drive({ auth: client }); const folderMetadata = { 'name': `Order_${order.key}`, 'mimeType': 'application/vnd.google-apps.folder' }; drive.files.create({ resource: folderMetadata, fields: 'id' }) .then((folder) => { console.log('Created folder Id: ', folder.id); }) .catch(err => console.error(err)) }) .catch((error) => console.error(error)); When building the code, I get the following error: src/assets-handler.ts:110:5 - error TS2345: Argument of type '{ resource: { 'name': string; 'mimeType': string; }; fields: string;...

TypeScript Inheritance and Constructor Arguments

Image
Clash Royale CLAN TAG #URR8PPP TypeScript Inheritance and Constructor Arguments Using Angular 5 and TypeScript, in the following inheritance scenario, is it possible to not have to include MyService as an argument to the constructor of MyComponent ? MyService constructor MyComponent export class CBasic { // properties and methods } export class CAdvanced extends CBasic { // constructor constructor( public myService: MyService ) { // call constructor of super-class (required) super(); } // more properties and methods } export class MyComponent extends CAdvanced { // constructor constructor() { // call constructor of super-class (required) super(); // Error: [ts] Expected 1 arguments, but got 0. } } The error I am getting is [ts] Expected 1 arguments, but got 0. in MyComponent . [ts] Expected 1 arguments, but got 0. MyComponent The point is I want to include MyService in CAdvanced to avoid code-duplication i...

A generic interface with type constraints accepting a default type

Image
Clash Royale CLAN TAG #URR8PPP A generic interface with type constraints accepting a default type I've created a simple generic interface in typescript interface DateAdapter<T> { clone(): T; } and I have a simple class which implements said interface class StandardDateAdapter implements DateAdapter<StandardDateAdapter> { clone: () => StandardDateAdapter; } I then have a generic Options interface which accepts a type extending DateAdapter . By default, I'd like the type argument to be StandardDateAdapter so I set it up like so: Options DateAdapter StandardDateAdapter interface Options<T extends DateAdapter<T> = StandardDateAdapter> { until?: T; } Unfortunately, typescript doesn't like this and is throwing an error Type 'StandardDateAdapter' does not satisfy the constraint 'DateAdapter<T>'. Types of property 'clone' are incompatible. Type '() => StandardDateAdapter' is not assignable to type ...

populate json content in table using angular6

Image
Clash Royale CLAN TAG #URR8PPP populate json content in table using angular6 I have json to construct table by populating its header and body dynamically. But my following table angular6 code is not populating as expected. Could anyone suggest the problem is in json or table iteration. Expected Output: JSON: this.columns = ["role1", "role2", "role3"]; this.permission = [ { role1: [{ master: { sub1: { read: true, write: true }, sub2: { read: true, write: true } }, support: { sub3: { read: true, write: false } }, admin: { sub4: { read: false, write: false } } }], role2: [{ master: { sub1: { read: true, write: false }, sub2: { read: true, write: false } }, support: { sub3: { read: true, write: true } }, admin: { sub4: { read: false, write: false } } }], role3: [{ master: { sub1: { read: true, write: true }, sub2: { read...

Angular 6 - Cannot Process data from web api

Image
Clash Royale CLAN TAG #URR8PPP Angular 6 - Cannot Process data from web api I am attempting to process some data from an api in Angular 6. However, even though I can see in Network tab that the data below is being returned, I cannot process the data after this call completes. My data returned by service: {"profile": "German DJ and producer based in Berlin. He is the founder of a label."} My fetch: public fetchData(): Observable<DiscogsRecord> { return this.http.get(this.url).pipe( map(response => response["profile"]), catchError(this.errorHandler("Error loading music data.", )) ); } My interface: export interface DiscogsRecord { profile: string; } My ngOnInit: ngOnInit() { this.recs = ; this.dataService.fetchData().subscribe(records => (this.recs = records)); console.log(this.recs); ... etc When I log this.recs, I get no data, just an empty array: . What am I doing wrong? Have you tri...

(TS) In 'const' enum declartions member initializer must be constant expression

Image
Clash Royale CLAN TAG #URR8PPP (TS) In 'const' enum declartions member initializer must be constant expression I've got problem with building application at Visual Studio 2017. I'm using ASP.NET CORE 2 and Angular 6. After running application i'm getting errors at file output_ast.d.ts from node_modules: (TS) In 'const' enum declartions member initializer must be constant expression. and Build:In 'const' enum declarations member initializer must be constant expression. Code with error: export declare const enum JSDocTagName { Desc = "desc", Id = "id", Meaning = "meaning", } My package.json "name": "client-app", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", ...

Image url still unsafe after I use DomSanitizer

Image
Clash Royale CLAN TAG #URR8PPP Image url still unsafe after I use DomSanitizer I use DocumentsService to get an image file from the server after that I use URL.createObjectURL(result) to create image url from server respond, everything seem working fine but I keep get a error about sanitizing unsafe URL and can't see the image. DocumentsService URL.createObjectURL(result) sanitizing unsafe URL @Injectable() export class DocumentsService { public url:string = 'api.server.url' constructor(private http: HttpClient , private dom: DomSanitizer) { } public getImageUrl(imageId: string): Observable<any> { let requestOptions = { params: { id: imageId }, responseType: "blob" }; return this._restClientService.get(this.url, requestOptions).map(result => { let url = URL.createObjectURL(result); return this.dom.bypassSecurityTrustUrl(url); }...