Array variable outside subscription is empty
My goal is to read a csv file into an array in an Angular app in TypeScript.
I created a function which subscribes to another function which returns an observable and puts its value in a variable.
processesData: any[] = new Array();
loadCvs(files: FileList) {
const file: File = files[0];
if(files && files.length > 0) {
this.getCsv(file).subscribe((output: any[]) => {
this.processesData = output.slice();
console.log(this.processesData);
});
console.log(this.processesData);
}
}
getCsv(file: File): Observable<any[]> {
const sub = new Subject<any[]>();
//File reader method
let reader: FileReader = new FileReader();
let tmp: any[] = new Array();
reader.onload = () => {
let csv: any = reader.result;
let allTextLines = [];
allTextLines = csv.split(/\r|\n|\r/);
const header = allTextLines[0];
const numberOfCols = header.split(',').length;
for(let i = 0; i < allTextLines.length; i++) {
let line = allTextLines[i];
let lineData = line.split(',');
if (lineData.length > numberOfCols) {
let temp = lineData.slice(1,3).join(',');
lineData[1] = temp;
lineData.splice(2, 1);
}
tmp.push(lineData);
}
sub.next(tmp.slice());
}
reader.readAsText(file);
this.initDrawFlow(this.drawFlowHtmlElement);
return sub.asObservable();
}
When I log this.processData inside the subscription everything seems to work fine. However, when I log it outside the variable is empty.
do you know?
how many words do you know
See also questions close to this topic
-
How to get only one question to the preview page in survey management website in angular?
I am using querystring to h=get the questions on preview page but I am not able to get one question on 1st page and 2nd on another page after clicking next button.
Querystring
const queryString = { SurveyId: 1, PageNo: 0, PageSize: 20 };
-
@Host() or ng-container incompatibility between angular 9 and 10
Here are two live examples on stackblitz:
To check the difference between them, open console and notice that:
In form-error-control-name.directive.ts line 22:
For angular 9, this.parent.control is not null For angular 10, this.parent.control will throw error
What is the difference? I checked angular 10 update doc but don't know which incompatibility this is.
Thanks!
-
How can I delete a row by its SKU instead of its ID?
I try to delete the row using the sku of the product. I'm using spring boot and angular. I got an error when I added the sku on my button like this one
(click)="onDeleteProductBySku(deleteClick?.sku)"
it said that theProperty 'sku' does not exist on type '(product: Product) => void'.
. On my command prompt, I got this error. How can I solve this problem?Error: product/product.component.html:50:109 - error TS2339: Property 'sku' does not exist on type '(product: Product) => void'. 50 <button class="btn btn-outline-danger btn-sm me-2" (click)="onDeleteProductBySku(deleteClick?.sku)">Delete</button> product/product.component.ts:12:16 12 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component ProductComponent.
ProductsController.java --> This is working on the postman.
//Delete a product record using sku //http://localhost:8080/products/deletebysku?sku=12345678 @DeleteMapping("/products/deletebysku") @ResponseBody private void deleteProductBySku(@RequestParam String sku){ productsService.deleteProductBySku(sku); }
product.component.ts
public deleteProduct!: Product; public onDeleteProductBySku(sku: string): void { this.productServive.deleteProductBySku(sku).subscribe( (response: void) => { this.messageShow(); console.log(response); this.getAllProduct(); }, (error: HttpErrorResponse) => { this.errorMessage(error.message); } ); } public deleteClick(product: Product) { this.deleteProduct = product; console.log("delete by sku"); }
product.service.ts
public deleteProductBySku(sku: string): Observable<void> { return this.http.delete<void>(`${this.apiServerUrl}/products/deletebysku?sku=${sku}`); }
product.component.html
<button class="btn btn-outline-danger btn-sm me-2" (click)="onDeleteProductBySku(deleteClick?.sku)">Delete</button>
-
How can I get toast-ui editor content?
I am a student studying. I think I'm doing it conceptually wrong.
I'm trying to use vue3 and type script And I'm going to use toast-ui editor.
I get some errors.
- refEditor.value.invoke is not a function
How can I get toast-ui editor content?
this is my code
<template> <div class="markup-tables flex"> <va-card :title="$t('tables.stripedHoverable')"> <va-card-content> <div id="refEditor" ref="refEditor"></div> <br /> <div class="row justify--end paginationButtons-left"> <va-button class="mr-2 mb-2">List</va-button> </div> <div class="row justify--end paginationButtons-right"> <va-button class="mr-2 mb-2" @click="getHTML">Save</va-button> </div> </va-card-content> </va-card> </div> </template> <script lang="ts"> import '@toast-ui/editor/dist/toastui-editor.css' import Editor from '@toast-ui/editor' import { defineComponent, onMounted, ref } from 'vue' import data from '@/data/tables/markup-table/data.json' export default defineComponent({ name: 'BoardWrite', setup() { const refEditor = ref(null) const getHTML = () => { console.log('getHTML test') let html = refEditor.value.invoke('getHtml') console.log(html) // ERROR } onMounted(() => { const editor = new Editor({ el: refEditor.value, height: '700px', initialEditType: 'markdown', previewStyle: 'vertical', }) editor.getMarkdown() }) return { getHTML, refEditor, } }, }) </script>
-
Custom utility types (generic types) for classes `IsClass` of TypeScript
I am trying to create a
generic type
to make sure the first parameter to be a class. However, the factory function parameter cannot be replaced by ageneric type
.The following upper parts were my attempts. The last part were a working example that directly write the
extends ...
which worked.Why does it works inside a function, but not works as a
generic type
IsClass
?class A { constructor() { } } class B {} class C extends B {} // ERRORS: type IsClass<T extends new (...args: any) => InstanceType<T>> = T type IsClass2<T> = T extends new (...args: any) => InstanceType<T>? T: never type X = IsClass<A> type Y = IsClass2<A> function someFactoryError<T>(clx: IsClass<T>) { return new clx() } someFactoryError(A) function someFactoryError2<T>(clx: IsClass2<T>) { return new clx() } someFactoryError2(A) // WORKS: function someFactoryWorks<T extends new (...args: any) => InstanceType<T>>(clx: T) { return new clx() } const a0 = someFactoryWorks(A) const b0 = someFactoryWorks(B)
Related:
-
Async function passed as prop into React component causing @typescript-eslint/no-misused-promises error
I have the following asynchronous submitNewPatient function which is throwing @typescript-eslint/no-misused-promises error message from elint. Is it possible to adjust the function such that it removes this error?
const submitNewPatient = async (values: PatientFormValues) => { try { const { data: newPatient } = await axios.post<Patient>( `${apiBaseUrl}/patients`, values ); dispatch({ type: "ADD_PATIENT", payload: newPatient }); closeModal(); } catch (e: unknown) { if (axios.isAxiosError(e)) { console.error(e?.response?.data || "Unrecognized axios error"); setError( String(e?.response?.data?.error) || "Unrecognized axios error" ); } else { console.error("Unknown error", e); setError("Unknown error"); } } };
Component used to pass function as a prop:
<AddPatientModal modalOpen={modalOpen} onSubmit={submitNewPatient} error={error} onClose={closeModal} />
I have also tried the following which removes the eslint error message based. However, seems like I am not entering the async code block (perhaps not triggering the async() function):
const submitNewPatient = (values: PatientFormValues) => { async () => { try { const { data: newPatient } = await axios.post<Patient>( `${apiBaseUrl}/patients`, values ); dispatch({ type: "ADD_PATIENT", payload: newPatient }); closeModal(); } catch (e: unknown) { if (axios.isAxiosError(e)) { console.error(e?.response?.data || "Unrecognized axios error"); setError( String(e?.response?.data?.error) || "Unrecognized axios error" ); } else { console.error("Unknown error", e); setError("Unknown error"); } } }; };
-
How to return Observable from Callback
I have a service in which I want to implement the logic of an SDK. From this SDK I want to call a callback function that returns me a payload.
I want to create a method in which the callback function is called but returns an Observable. As well I have created an interface to describe what is required (variables I get from the sdk). Is this the right approach at all?This is what I created so far:
export interface SdkPayload{ avatar, name, jobTitle, availability } export class TestService { sdk:someSDK; getPayload$(): Observable<SdkPayload[]> { return new Observable<SdkPayload[]>((subscriber) => { const callbackFunction = (sdkPayload) => { //do I here call the function from the sdk?? this.someSDK.on('connected', (payload) => { //how to return the payload and how to assign it to interface? const { customer, availability, greeting } = payload payload.greeting.agent.avatar, payload.greeting.agent.name, payload.greeting.agent.jobTitle, payload.availability; }); /** Emit the callback response to the Observable **/ subscriber.next(sdkPayload); }; this.customerSDK.on('connected', callbackFunction); return () => { this.customerSDK('off', callbackFunction); }; }); }
Component:
export class AppComponent{ payloadResults$: Observable<SdkPayload[]>; constructor (private service:TestService){} callMethod(){ this.payloadResults$=this.service.getPayload$(); } }
Template:
<ul *ngFor="let result of payloadResults$|async"> //how to call the variables: image, name etc (the ones get from the sdk event) <ul></ul> </ul>
-
Merge my initial state with data from API
I don't understand why my state data was not merged with my initial state
In my initial state i have:
data: {role: null, lastUrl: null},
When my call api is over, my state is updated with the data from API but my role and last URL property disapears.
I want to update the data of my state with the data from API and add the two properties of my initial state.
Can you explain to me what I've missed please?
For the more important files in my store i have:
One init.model.ts:
export interface Initialization { role: string, lastUrl: string, }
One init.actions.ts:
import { Action } from "@ngrx/store"; import { Initialization } from './init.models'; export enum Types { INIT = '[Init] Start', INIT_SUCCESS = '[Init] SUCCESS', INIT_ERROR = '[Init] ERROR', } // Init export class Init implements Action { readonly type = Types.INIT; constructor() { } } export class InitSuccess implements Action { readonly type = Types.INIT_SUCCESS; constructor(public data: Initialization) { } } export class InitError implements Action { readonly type = Types.INIT_ERROR; constructor(public error: string) { } } export type All = Init | InitSuccess | InitError;
One init.reducers.ts
import { Initialization } from './init.models'; import * as fromActions from './init.actions' export interface InitState { data: Initialization; loading: boolean; error: string; } const initialState = { data: {role: null, lastUrl: null}, loading: null, error: null, } export function reducer(state: InitState = initialState, action: fromActions.All) { switch (action.type) { // Init case fromActions.Types.INIT: { return { ...state, loading: true, error: null }; } case fromActions.Types.INIT_SUCCESS: { return { ...state, data: action.data, loading: false, error:null }; } case fromActions.Types.INIT_ERROR: { return { ...state, loading: false, error: action.error }; } default: { return state; } } }
One init.effects.ts:
import { map, switchMap, catchError } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { Observable, of } from 'rxjs'; import * as fromActions from './init.actions'; import { ConfigService } from '@app/services/config/config.service'; type Action = fromActions.All; @Injectable() export class InitEffects { constructor( private actions: Actions, private config: ConfigService, ) { } init: Observable<Action> = createEffect(() => this.actions.pipe( ofType(fromActions.Types.INIT), switchMap(() => { return this.config.load().pipe( map( init => { return new fromActions.InitSuccess(init || null) } ), catchError(err => of(new fromActions.InitError(err.message))) ); }) ) ) }
-
Angular RxJS - Subscribe to Observable only IF subscribing to another Observable gave a certain result
I need some kind of special RxJS syntax if it exists for this scenario:
this.electronicInvoiceService.getElectronicInvoice(this.invoiceId) .subscribe(and here I can get .isApproved, for example: (data) => data.isApproved and what I want is IF data.isApproved is false only then I want to subscribe to this next observable I wrote below this);
do this next subscribe only if isApprove is false
this.electronicInvoiceStagingService.getElectronicInvoice(this.invoiceId).subscribe();
What I tried already: I tried to have some variable in in my ts file and inside subscribe I did this.myVariableName == data.isApproved but this did not work I think because subscribing takes some time and it was bad logic.
[SOLUTION]: The comment below solved it, its silly of me I didnt use it right away (: solution> Why is a simple if statement not sufficient? (data) => {if (!data.isApproved) this.electronicInvoiceService.getElectronicInvoice(this.invoiceId).subscribe();}
-
RXJS conditionally call observable
const observable$ = iif(() => this.shippingTabModified, //Shipping Tab Modified True of(this.updateShippingInfo()) .pipe(), //IF Shipping Tab Not Modified of(this.shippingInfoService.getShipmentInfoByCardIdObservable(this.data.CardId)) .pipe() ) observable$.subscribe();
From above code i want to achieve following scenario
if(foo === true) { updatemethod() } // if foo is true and update method is executed we need to wait until update method is finished then go to second method // If foo is false we can call second method without waiting secondmethod();
But from rxjs code which i wrote above, it always go to update method it is not considering the value of
this.shippingTabModified
-
How to get the multiple observables from one observable of API Response in Angular
I am trying to get the data from the API response it's having some properties the thing is i need to map and treat each property as observable because i am sending those observables to the child component to bind the data the following one is a samle response so i need to take the data part from there and i need to have a data1 as one obsarvable data2 as another one and so on
{ PageDetails: 'pagedetails', data: { data1: [], data2: [], data3: [], data4: [] } }