can't read property inside .subscribe
I've a problem with a loop which actually works but give me this error in the console:
ERROR TypeError: Cannot read property 'X' of undefined
Here is the code:
for (let counter = 0; counter < this.signs.length; counter++) {
if (this.sign === this.pairs[counter].value) {
this.collectService.getSign(this.sign).subscribe(data => {
// value X, I try and I export but give me an error
this.X = data.sign.toString();
this.changeComponent(this.sign1, this.sign2, this.X);
});
}
}
So, one more time, it works but why do I have this error?!
See also questions close to this topic
-
Creating a linked list object using js
I want to make a linked list using
custom Object
that pushes a value, pop a value, display all its content, remove an item from a specific place, and insert at a specific place as long as the value is missing from the sequence otherwise through an exception. All of the properties should be defined using data descriptor, prevent them from being deleted, iterated, or being modified.I can do no more than this ... I'm new to js.
var linkedList = {}; /* linkedList.name = 'Ahmed'; [].push.call(linkedList, 'sad', "sd"); */ Object.defineProperty(linkedList, "name", { value: "mohamed", writable: false, configurable: false, enumerable: false }) linkedList.next = {'sd':'as'};
Any help? thanks in advance
-
Trying to trigger a CSS animation with a button press through Javascript
I'm trying to trigger a CSS animation with a button press by using Javascript. I've used other question and answers here, but to no avail. My code seems like it should work -- what am I missing? When I click the button, the background color of the div which I specify should change color over 2 seconds to light blue. I've tried changing the color of both my Body and my Test div, but nothing changes. My alert() triggers, which is confusing as it is in the same function as my colorChange.
<!DOCTYPE html> <html lang="en"> <head> <title><model-viewer> example</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script> function colorChange() { alert("The button works"); document.getElementByID('test').style.animation="changeColor"; } </script> <style> body { background-color: darkblue; -webkit-transition: all 2s ease; -moz-transition: all 2s ease; -o-transition: all 2s ease; -ms-transition: all 2s ease; transition: all 2s ease; } .test { width: 500px; height: 500px; background-color: pink; } @keyframes changeColor { to { background-color: lightblue; } } </style> </head> <body id="body"> <div class="test"></div> <button id="button" onclick="colorChange()">test animation</button> </body> </html>
-
No output from (GET) Ajax Result From Php Array with json_encode
I have a GET form that gets a Php Array and json encodes it. The Issue I am having is the succes data is not displaying. I want the success to display data in a Alert or console but for some reason its not working. I have tried many options. Thanks for your help.
PS:I know the GET and all files work because when I got the script the Ajax reponse result would populate/append a Table sucessfully. I am modifing it.
Here is the php index file with the AJAX:
<!doctype html> <html> <head> <title>Return JSON response from AJAX using jQuery and PHP</title> <link href="style.css" type="text/css" rel="stylesheet"> <script src="jquery-3.1.1.min.js" type="text/javascript"></script> </head> <body> <script> $(document).ready(function(){ $.ajax({ url: 'ajaxfile.php', type: 'get', dataType: 'JSON', success: function(data){ var obj = jQuery.parseJSON(data); alert(obj.username); } }); }); </script> </body> </html>
Here is the php file that quries the database and encodes/array json:
<?php $return_arr = array(); $sql = "SELECT * FROM users ORDER BY NAME"; $result = $conn->query($sql); //Check database connection first if ($conn->query($sql) === FALSE) { echo 'database connection failed'; die(); } else { while($row = $result->fetch_array()) { $id = $row['id']; $username = $row['username']; $name = $row['name']; $email = $row['email']; $return_arr[] = array("id" => $id, "username" => $username, "name" => $name, "email" => $email); } // Encoding array in JSON format echo json_encode($return_arr); } ?>
echo json_encode array output from the php file looks like below (test content):
[{"id":"1","username":"jiten","name":"Jiten singh\t","email":"jiten9"},{"id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldee"},{"id":"3","username":"mayank","name":"Mayank","email":"mayank"},{"id":"9","username":"mohit","name":"Mohit","email":"mohit"},{"id":"13","username":"mukesh","name":"Mukesh","email":"mukesh"},{"id":"6","username":"nitin","name":"Nitin","email":"niti"},{"id":"12","username":"palash","name":"Palash","email":"palash"},{"id":"7","username":"rahul","name":"Rahul singh","email":"rahul"},{"id":"10","username":"rohit","name":"Rohit singh","email":"rohit"},{"id":"8","username":"shreya","name":"Shreya","email":"shreyam"},{"id":"11","username":"sonarika","name":"Sonarika","email":"sonarika"},{"id":"5","username":"vijay","name":"Vijay","email":"vijayec"},{"id":"14","username":"vishal","name":"Vishal Sahu\t","email":"visha"},{"id":"4","username":"yssyogesh","name":"Yogesh singh","email":"yoges"}]
when I make the success result (data) and alert(data), this is what I get,empty objects
-
Creating two value range slider from Angular material native component
I need a two value range slider for my app, however none of the packages that I've looked at on NPM etc are 100% suitable for what I need. The Angular Material slider is the most suitable, however it doesn't allow for two values to be used on a single slider.
To get around this, I've had an idea of placing one slider on top of the other, to give the impression of one slider with two values. This works well, and has a smooth behaviour which is one of the requirements that I wanted my slider to have.
However, I would also like to add a bar in between the two slider thumbs, so that the selected range is highlighted and visible. The native slider does have this, but since it only allows one value the highlight starts from 0 and extends to the value of the slider.
Instead I want to have the highlight between the upper and lower values of the thumbs on the slider. But I have no idea how to add this to it. So I was wondering if someone could help me out. I'm not entirely sure if I'd need to add a new element on top of the bar that adjusts to the size between the two thumbs or if I'd have to do something different.
Alternatively if anyone knows how to make NGX-slider allow a smooth step like the angular material slider that would be the best solution and I'd love to hear it. https://www.npmjs.com/package/@angular-slider/ngx-slider
https://angular-9-material-starter-5ueh7p.stackblitz.io
Code so far
<mat-slider class="slider-left"></mat-slider> <mat-slider class="slider-right"></mat-slider> .slider-right { position: relative; left: -128px; } ::ng-deep .mat-slider-track-fill { background-color: rgba(0, 0, 0, 0.26) !important; } ::ng-deep .mat-slider-track-background { background-color: rgba(0, 0, 0, 0.26); }
-
Angular 10 form action not getting variable
I am creating a form in angular, used from a 3rd party, which needs to redirect away from my site for a payment and back.
I have added their sample code (the form which does a post) into my angular app and added a formGroup, and an action to the form (the action is the url I want to redirect to).
<form [formGroup]="tdsvt" (ngSubmit)="onSubmit2021" method="post" id="redirectForm" action="{{redirectUrl}}"> <input type="hidden" name="id" formControlName="reqID" /> </form>
I have changed the action to the variable that is needed, but it does not redirect and it stays blank. I have tried doing a normal post request and subscribe like so:
return this.http.post<any>(redirectUrl, data);
But I am hit with a CORS issue as it is a total different URL.
How can I get the action to work as a variable and redirect? Or if I shouldn't use an action, what's the best method around this?
Thank you
-
Child route with fragment
I have a page with a side menu, each side menu item has a routerLink that sends a different fragment. I want to know if it is possible that this new route with the fragment has a child route.
Example:
Side menu:
<button type="button" routerLink="['/pageA']" fragment="frag">btn side menu</button>
On click this button, the route would look like this: http://localhost:4200/#/pageA#frag
Content Page
<button type="button" routerLink="['child-a']">A</button> <button type="button" routerLink="['child-b']">B</button> <router-outlet></router-outlet> // Here son A or son B will be loaded
And when click on button A, the route would look like this: http://localhost:4200/#/pageA#frag/child-a
page-routing.module.ts
const routes: Routes = [ { path: '', component: PageAComponent, children: [ { path: 'child-a', component: ChildAComponent, }, { path: 'child-b', component: ChildBComponent, }, ], }, ];
-
setting a type only for the value of an object
I have this object:
const theme = {}
This object is being filled by a function, this function adds a property to this object whenever it's called, the key it sets is a random number as a string, so "1", "31" and so on, and the value it sets is a string.
I was looking for something like this in TypeScript:
interface Theme { string: string } const theme: Theme = {} const theFunction(){ const key = `${Math.floor(Math.random() * 1000)}`; const value = "value"; theme[key] = value; }
The theFunction might get called at any unknown time,
-
How to format "2021-01-19T12:50:00Z" to: 2021-01-19 12:50:00
I am using angular and rxjs.
So I have this:
x: console.log(res.map(date => date.dt))
And it returns this:
0: "2021-01-19T12:50:00Z" 1: "2021-01-19T12:51:00Z" 2: "2021-01-19T12:52:00Z" 3: "2021-01-19T12:53:00Z" 4: "2021-01-19T12:54:00Z" 5: "2021-01-19T12:55:00Z" 6: "2021-01-19T12:56:00Z" 7: "2021-01-19T12:57:00Z" 8: "2021-01-19T12:59:00Z"
But of course that is not readable.
SO I want to convert it to for example this: '2021-01-19 12:50:00',
So: yyyy-MM-dd HH-MM-SS
But so what I have to change?
Thank you
-
loop through variables names in Python
I am working in Python. I have a dataframe called df with 3 columns: a, b, c. I want to do a loop which loops through all variables and generates a numpy array for each variable and cuts the last number of each variable. So far I have tried, but it is not working:
df = pd.DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['a', 'b', 'c']) variables= [a,b,c] for x in variables: x = np.transpose(np.matrix(df.x.to_numpy(np.float64))) x=x[:-1]
-
For loop creates NA after 2th row
I'm trying use first row and repeat same process for last row.
mt0 <- 15 c0 <- 1.2 F <- 1 W <- 0.55 V <- 1.5 yt_value_test <- c(16.28948, 15.07612, 14.68842, 16.13255, 14.21511, 14.10924, 14.18346, 15.46259) Mt_index <- mt0 Ct_index <- W + c0 Ot <- F*Mt_index Qt <- V+F^2 Mt <- Mt_index + Ct_index*F*(Qt^-1)*(yt_value_test[1] - Ot) Ct <- Ct_index - (Ct_index*F*(Qt^-1)*Ct_index) table2 <- as.data.frame(cbind(Mt_index, Ct_index, Ot, Qt, Mt, Ct)) attach(table2) show(table2)
output:
> table2 Mt_index Ct_index Ot Qt Mt Ct 1 15 1.75 15 2.5 15.90264 0.525
For loop I'm using above process for data[i], second created like just like I wanted, but after that loop creates NA
for (i in 1:8) { Mt_index <- Mt[i] Ct_index <- W + Ct[i] Ot <- F*Mt_index[i] Qt <- V+F^2 Mt <- Mt_index[i] + Ct_index[i]*F*(Qt[i]^-1)*(yt_value_test[i] - Ot[i]) Ct <- Ct_index[i] - (Ct_index[i]*F*(Qt[i]^-1)*Ct_index[i]) table2 <- rbind(table2, c(Mt_index, Ct_index, Ot, Qt, Mt, Ct)) }
output creates NA which I don't know why
> table2 Mt_index Ct_index Ot Qt Mt Ct 1 15.00000 1.750 15.00000 2.5 15.90264 0.52500 2 15.90264 1.075 15.90264 2.5 16.06898 0.61275 3 NA NA NA 2.5 NA NA 4 NA NA NA 2.5 NA NA 5 NA NA NA 2.5 NA NA 6 NA NA NA 2.5 NA NA 7 NA NA NA 2.5 NA NA 8 NA NA NA 2.5 NA NA 9 NA NA NA 2.5 NA NA >
second row is correct what I tried to do. 3th row should start Mt_index[3] Mt[2] which is 16.06898. Like first row Mt values second row Mt_index values.
-
For loop help needed
I have this code that is giving me an error:
list = [] for num, i in enumerate(data[1:], 1): if ((i-1) > 0) and (i < 0): list.append(num)
This updated code works. I am trying to implement this to detect sign change in an array that goes from positive to negative. SO the two conditionals of
i-1
andi
help distinguish an instance when it goes from positive to negative. However, the list.append(num)
is now having issues because it is not populating. I believe it to be an issue of not knowing whatnum
to append. Any insights? -
I can't access variables in class using this
class main { constructor(client) { this.client = client; console.log(this.client); //is set } test2() { console.log(this.client); //undefined } }
For some reason i can't get it to get this.client in the function. Am i missing something? I am calling the class like this:
let plData = pl.js(); let plFile = require(file + "/" + plData.file); //Will require index.js this[plData.friendlyname] = {}; //create empty json based on class name so i can put functions in it later. let plClass = new plFile.main(this); //create class with the this of the current class containing some info it has to use. I need to pass the this of this class on to the new class plFile.exp.forEach((func, i) => { //at bottom of code i export exp containing every function's name of the class this[plData.friendlyname][func] = plClass[func] //set thisclass.friendlyname.functionname to newClass.function })
No idea why it doesn't work
-
While Routing in Submodules Reducers Initial State comes undefined after migration Angular Version from 8 to 9
Angular version upgrade from 8 to 9 done smoothly. While routing I am able to load my submodules but the reducers state comes undefined with lazy loading.
Package.json:
"dependencies": {
"@angular/animations": "9.1.13", "@angular/cdk": "8.0.0", "@angular/common": "9.1.13", "@angular/compiler": "9.1.13", "@angular/core": "9.1.13", "@angular/forms": "9.1.13", "@angular/http": "7.1.3", "@angular/localize": "^9.1.13", "@angular/platform-browser": "9.1.13", "@angular/platform-browser-dynamic": "9.1.13", "@angular/router": "9.1.13", "@ng-bootstrap/ng-bootstrap": "^4.0.0", "@ngrx/effects": "^6.0.1", "@ngrx/entity": "^6.0.1", "@ngrx/router-store": "6.1.2", "@ngrx/store": "^7.4.0", "@nrwl/nx": "7.8.6", "@swimlane/ngx-charts": "^12.0.1", "c3": "^0.7.11", "core-js": "^2.5.4", "d3": "^5.14.2", "error-stack-parser": "^2.0.2", "g": "^2.0.1", "handlebars": "4.5.0", "ng2-search-filter": "^0.5.1", "ngx-toastr": "^9.0.2", "rxjs": "^6.5.2", "rxjs-compat": "^6.1.0", "tslib": "^1.9.0", "web-animations-js": "2.1.5", "zone.js": "^0.10.3"
}
app.module.ts :
imports: [
ToastrModule.forRoot({ tapToDismiss: false, closeButton: true, positionClass: 'toast-top-center' }), NxModule.forRoot(), StoreModule.forRoot(reducers, { metaReducers }), EffectsModule.forRoot([AccountEffects, MegaMenuEffects, ProjectEffects, NotificationDropDownEffects]), StoreDevtoolsModule.instrument({ maxAge: 50 }), ScrollingModule
]
app.routing.module.ts:
const routes: Routes = [ { path: "segmentation", loadChildren: "@aps-uisuite/modules/aps_segmentation/segmentation-ui-angular/segmentation#SegmentationModule", canActivate: [AuthGuard], }, { path: "", redirectTo: "dashboard", pathMatch: "full", }, ];
submodule.module.ts:
imports: [
AppSharedModule, DashboardModule, StoreModule.forFeature('segmentation', fromReducer.reducer), StoreModule.forFeature('variables', variableReducer.reducer, { initialState }), StoreModule.forFeature('parameters', parameters.reducer), StoreModule.forFeature('jobs', jobs.reducer), EffectsModule.forFeature([SegmentationEffects, VariablesEffects, ParametersEffects, JobsEffects])
]
-
Vue.js cannot read the property of a json object brought from STRAPI
I'm using VUE.JS and I want to display an image of a json object brought in from an API built with STRAPI but it throws the following error.
[Vue warn]: Error in render: "TypeError: Cannot read property 'url' of undefined".
En la plantilla vue, he probado con
<v-card v-bind:img-src="menu.image[0].url" v-bind:title="menu.name" style="max-width:20rem">
and with:
<v-card v-bind:img-src="menu.image.url" v-bind:title="menu.name" style="max-width:20rem">
in both it gives the same error
This is the json:
[ { "_id": "60035145339db62a385ba032", "name": "Buffalo Wings", "quantity": "15 piezas", "price": "26000", "description": "Trozos de alitas de pollo apanadas,", "time": "15 minutos", "createdAt": "2021-01-16T20:49:09.235Z", "updatedAt": "2021-01-16T21:15:33.095Z", "__v": 0, "image": { "_id": "60035762339db62a385ba038", "name": "buffalo-wings-2-800x600.jpg", "hash": "buffalo_wings_2_800x600_dd299e2810", "ext": ".jpg", "mime": "image/jpeg", "size": 78.55, "width": 800, "height": 600, "url": "/uploads/buffalo_wings_2_800x600_dd299e2810.jpg", "provider": "local", "related": [ "60035145339db62a385ba032" ], "id": "60035762339db62a385ba038" }, "id": "60035145339db62a385ba032" }
]
This is the script
await fetch("http://localhost:1337/menus").then( (res) => res.json() ).then((data) => { this.menus = data; }); console.log(this.menus);