How to get a value from a subcribe - javascript

I would like to know how I can get a value that I have in a subscribe pass it to a variable and be able to manipulate it example
getNumber: number;
I want in the same .ts to use that variable getNumber
someMethodTwo() {
this.someMethod().subscribe(data =>
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'it's is the variable '+ getNumber ,
showConfirmButton: false,
timer: 1500
})
}
someMethodOne() {
this.someMethod().subscribe(data =>
this.getNumber= data);
}

if someMethod returns an observable you can use
.pipe(map(value => {
// manipulate value here and return it
}
)).subscribe((value) => {
this.yourlocalvaribale = value
)

Related

Getting metadata information from an Observable while executing inside another Observable

I have some song information that I need to add metadata too. I am looking to combine this using one Observable execution (sorry if my terminology is wrong). But I can't get the metadata in the final map
First Attempt:
songsViewData = combineLatest([
this.songs,
this.genre,
]).pipe(
map(([songs, genre]) => {
let query = {
filename: songs[genre],
song_id_range: 50,
filenames_included: true
}
// This doesn't return the inner object. Just an observable
return this.getSongData(query).subscribe((metaData) => {
return (songs[genre]).map((song) => {
return {
id: song,
songTitle: metaData[song].songTitle,
artistName: metaData[song].artistName
}
})
})
})
)
Second Attempt:
songsViewData = combineLatest([
this.songs,
this.genre,
]).pipe(
switchMap(([songs, genre]) => {
let query = {
filename: songs[genre],
song_id_range: 50,
filenames_included: true
}
return this.getSongData(query) // This gets the metadata
}),
map(([songs, genre, metaData]) => { // I want to access the metadata here
return (songs[genre]).map((song) => {
return {
id: song,
songTitle: metaData[song].songTitle,
artistName: metaData[song].artistName
}
})
})
)
You can use a forkJoin in which you wrap both the switchMap and also the other values you need. This only works if this.getSongData completes. Otherwise, take combineLatest instead.
songsViewData = combineLatest([
this.songs,
this.genre,
]).pipe(
switchMap(([songs, genre]) => {
let query = {
filename: songs[genre],
song_id_range: 50,
filenames_included: true
}
return forkJoin([of([songs, genre]), this.getSongData(query)])
}),
map(([[songs, genre], metaData]) => {
return (songs[genre]).map((song) => {
return {
id: song,
songTitle: metaData[song].songTitle,
artistName: metaData[song].artistName
}
})
})
)

How to change param from outside

I need to change lang value on export const GetWeatherDetails = ( location ="Paris", lang= 'en'), what would be the proper way to do it, it's an Action.js file so I need to get it done from App.js or another file in this case I got Weather.js
export const GetWeatherDetails = ( location ="Paris", lang= 'en') => async dispatch => {
dispatch({ type: GET_WEATHER.PENDING });
axios
.get(BASE_URL, {
params: {
q: location,
lang: lang,
units: "Metric",
}
})
.then(response =>
dispatch({ type: GET_WEATHER.SUCCESS, payload: response.data })
)
.catch(err => {
console.log(err.response, err);
toast.error(err.response.data.message, {
position: "bottom-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: false
});
dispatch({ type: GET_WEATHER.REJECTED, payload: err.response });
});
};
As #IronGeek pointed out, lang is the second argument to the GetWeatherDeatils function. It's predefined with the "en", so that if you call GetWeatherDetails without the second argument, "en" is used. For example:
GetWeatherDetails('Berlin')
If you want to pass in another value, just call GetWeatherDetails with other values:
GetWeatherDetails('Berlin', 'de')
You can read more about default function arguments at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

How to call a function in setup() to a function in methods?

I have function in setup() named onRquest, I want to call that function in methods after execution of an action(deleting row), which gonna refresh the table. Please check the code segment for better understanding:
export default {
setup() {
function onRequest(props) {
}
onMounted(() => {
onRequest({
pagination: pagination.value,
filter: undefined,
})
})
return {
onRequest
}
},
methods: {
deleteBranch(branch_id) {
this.$q.dialog({
title: 'Confirm',
message: 'Would you like to Delete Branch#' + branch_id + '?',
cancel: true,
persistent: true
}).onOk(() => {
this.$axios.delete('https://api.bdshsystem.com/api/v1/branch/' +
branch_id).then(response => {
this.$q.notify({
type: 'positive',
timeout: 500,
position: 'top',
message: 'Branch Deleted Successfully !'
})
I want to put function onRequest Here
}).catch((error) => {
this.$q.notify({
type: 'negative',
position: 'top',
timeout: 500,
message: 'Form submission Failed !'
})
})
}).onOk(() => {
// console.log('>>>> second OK catcher')
}).onCancel(() => {
// console.log('>>>> Cancel')
}).onDismiss(() => {
// console.log('I am triggered on both OK and Cancel')
})
},
},
}
Insted of passing you method inline i.e. the "setup()" method, directly in export default. define it outside and pass its reference to export default then you can call setup() directly in whatever method you want
function setup(){
//some code
}
export default {"setup":setup,
"yourOtherMethod":function yourOtherMethod(){
//your other method code here
}}

TypeError: Cannot read property 'caption' of undefined

Trying to test if the following function gets called correctly.
Here is the function, using Jest and Enzyme for React Js:
changeCurrentColumn = (e) => {
{
if(e.target.value !== 'default')
{
const id = e.target.value
const name = this.props.defaultData[e.target.value].caption
this.props.setCurrentColumn({ name, id })
}
}
}
Here is the test:
it('changeCurrentColumn function test', () => {
wrapper.setProps({
defaultData:[{
caption:"test"
},],
}),
wrapper.update();
The error is pointing to ({target:'test'})) :
expect(wrapper.instance().changeCurrentColumn({target:'test'})).toBeDefined();
})
What can I add after 'test' in order to read the property of 'caption'?
Thanks.
You can change the type of the defaultData to object something like this.
it('changeCurrentColumn function test', () => {
const event = {
target: {
value: "caption"
}
}
wrapper.setProps({
defaultData:{
caption:"test"
},
}),
wrapper.update();
expect(wrapper.instance().changeCurrentColumn(event)).toBeDefined()
});
or pass value as 0 to get rest from the existing defaultData.
it('changeCurrentColumn function test', () => {
const event = {
target: {
value: 0
}
}
wrapper.setProps({
defaultData:[{
caption:"test"
}],
}),
wrapper.update();
expect(wrapper.instance().changeCurrentColumn(event)).toBeDefined()
});

javascript promise inside object

I can get to work a promise inside the object "addable:". after saving the new client the id added to the slimselect need to wait for the new _id.
Thanks
Pay to*
var Datastore = require('nedb');
var dclipro = new Datastore({filename: '/data/clipro.db', autoload: true});
var selectclipro = new SlimSelect({
select: '#bcofid_clipro',
valuesUseText: false,
addable: function (value) {
var newid = "";
var agrabar = {
name: value,
last_idcuenta: "null",
email: "notdefined#gmail.com",
memo: "not available",
auditlog: moment().format('MMMM Do YYYY, h:mm:ss a')
}
dclipro.update({name: value}, agrabar, options, function (err, numReplaced, upsert) {
if (err) {
console.error(err);
}
newid = upsert._id;
})
iziToast.show({
title: 'Bank',
message: 'New Payee has been saved successfully',
position: 'topRight'
});
return { text: value, value: newid }
},
onChange: (info) => {
console.log('elegido : value ' +info.value);
console.log('elegido : text ' +info.text);
}
})
SlimSelect, wow is this thing dated. From the documentation, it looks like your return object is optional, and that you should be able to do something like selectclipro.setData(myNewValue) inside your promise callback, as long as addable can actually see selectclipro. (Make sure you read the rest of my comments above)

Categories