what will export { foo as bar } affect when importing module - ecmascript-6

I am confused about this snippet here.
//------ underscore.js ------
export default function (obj) {
...
};
export function each(obj, iterator, context) {
...
}
export { each as forEach };
//------ main.js ------
import _, { each } from 'underscore';
...
The export { each as forEach } part confused me.
When I import this function, should I use
import { each } from 'underscore' or import { forEach } from 'underscore'?
When I use the function in main.js , what will be the difference between export { each } and export { eash as forEach } ?

The export { each as forEach } part confused me.
It means "export the value of the local variable each under the name forEach".
When I import this function, should I use import { each } from 'underscore' or import { forEach } from 'underscore'?
import { forEach } from 'underscore'
because that's what the module exports.
When I use the function in main.js , what will be the difference between export { each } and export { eash as forEach } ?
export {each} exports the value under the name each. For the other see my first answer.
There wouldn't be any difference using the function except that you'd use a different name.
FWIW, the same thing can be done on the import side:
import { forEach as foo} from 'underscore'
Now you can refer to that function as foo instead of forEach.

Related

Deserialize and cyclic dependencies in Angular

I have several model.ts files.
When I use httpClient, I get a JSON object, but it does not work correctly since I have to deserialize them: How to recursively init class get by httpclient.
BUT since so, I found the project "class-transformer" that help me deserialize all my models.
I have in my services:
public method(cli: any): Observable<A> {
const formData = new FormData();
formData.append('cli', JSON.stringify(cli));
return this.http.post<A>('/my/url',
formData, {
withCredentials: true
}).pipe(first(),
map(res => {
return plainToClass(A, res);
})
);
}
And for models something like:
// A.model.ts
import { Type } from 'class-transformer';
import { B } from './B.model';
export class A {
// Some properties
#Type(() => B)
b: B[]
// Some methods
}
And B
// B.model.ts
import { Type } from 'class-transformer';
import { A } from './A.model';
export class B {
// Some properties
#Type(() => A)
a: A[]
// Some methods
}
But, when compiling I got "Circular dependency" and indeed there is a circular dependency...
Looking for solution I understant that I can use a Barrel (https://github.com/typestack/class-transformer/issues/230) but it did not work.
My only constraint is that I have to keep this relation -> (or something really similar since I can not modify the backend and so data I will receive with httpClient).
Any idea on how to fix the cyclic dependency?
Finally, I used the barrel solution. It appears that in the rest of my code there were import of class A directly, I changed them to use the barrel and everything works (I still have warnings. But it works)
// C.model.ts
// the problem is here
import { A } from './bla/A.model';
export class C {
}
// C.model.ts
import { A } from './bla';
export class C {
}
And at ./bla I have a index.ts with all the model export

ES6 import function - execute in Vue component

In my Vue app I have JS file with some config data. In JS file there is export function. I'm importing this function to my Vue component but it's returning function declaration as a string. How can I make that function to return it's return data?
JS file
export function Test(app) {
return [ some data... ]
}
Vue component
import { Test } from '#/config/Test'
export default {
data() {
return {
testData: Test,
}
},
}

Parse a json data from internal json file using Angular throwns error

I tried to get json from tne internal json file within angular.
with this service (village.service):
import { Injectable, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
#Injectable()
export class RecordsService {
data: any;
constructor(private http: Http) { }
getVillages(id) {
return this.http.get('../assets/data/villages.json')
.map(data => {
this.data = data.json();
return data.json();
}, err => {
if (err) {
return err.json();
}
});
}
}
and under commponet i put the:
ngOnInit() {
this.getVillages();
....
}
and here to load as the chain dropdown
onSubDistrictSelected(subDistrictId: number) {
if (subDistrictId) {
this.onLoading.emit(true);
this.customer.subDistrict = this.subDistricts.filter(c => (c.id == subDistrictId))[0].name;
this.customer.sdid = subDistrictId;
this.customer.subDistrictId = subDistrictId;
this.villages = this.getVillages().filter((item) => {
return item.subDistrictId === Number(subDistrictId)
});
this.onLoading.emit(false);
}
}
I got error when compile said: this.getVillages is not function, But is working correctly if i put the json value inside the component file:
getVillages() {
return [
{ json_data}
]
}
What I want to achieved is I want to used the JSon file instead put directly inside the commponet.
Thanks,
getVillages is a method in service, so you need to instantiate the service before you use it.
First you need to provide the RecordsService in a module, like,
app.module.ts
...
providers : [
RecordsService
]
...
And in your component,
abc.component.ts
constructor(public recordService : RecordsService) {
}
ngOnInit() {
this.recordService.getVillages();
}
Let me know if you still get the error or have some different error.
EDIT:
getVillages() is returning an Observable, so you need to subscribe in order to use the data returned.
this.recordService.getVillages().subscribe( data => {
console.log(data);
} )

property dispatch does not exist on type 'Observable<any>' issue when using redux in angular 6

I am trying to do simple redux application with angular 6.
reducers.ts
import { login,logout } from '../actions/actions';
export interface appReducer {
login:boolean,
user:String
}
const initialstate:appReducer={
login:false,
user:'guest'
}
export function reducer(state=initialstate,action):appReducer {
switch(action.type) {
case login:
return {...state,login:true,user:action.payload}
case logout:
return {...state,login:false,user:action.payload}
}
return state;
}
actions.ts
export const login="LOGIN";
export const logout="LOGOUT"
index.ts
import { reducer,appReducer } from './reducer';
import { ActionReducerMap } from '#ngrx/store';
interface appState {
appReducer:appReducer;
}
export const reducers:ActionReducerMap<appState>= {
appReducer:reducer
}
records.service.ts
import { Injectable } from '#angular/core';
import { HttpClient,HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
import { Store } from '#ngrx/store';
export class RecordsService {
getLogin:boolean=false;
constructor(private http:HttpClient,private store:Store<any>) {
this.recordFunc();
}
getState() {
return this.store.select('appReducer');
}
updateState(action) {
if(action.login==true) {
return this.store.select('appReducer').dispatch({
type:'LOGIN',
payload:action.uname
})
}
else {
return this.store.select('appReducer').dispatch({
type:'LOGOUT',
payload:action.uname
})
}
}
}
in the above code I created reducers and successfully registered within the store module.Then I import the store in my service(records.service.ts) file.By subscribing into my getState() I get my current state but when I calling the updateState() to dispatch an action for updating the state it shows following error in my terminal and also update my state.
ERROR in src/app/records.service.ts(69,44): error TS2339: Property 'dispatch' does not exist on type 'Observable<any>'.
src/app/records.service.ts(75,42): error TS2339: Property 'dispatch' does not exist on type 'Observable<any>'.
I face the same issue and found a quick fix.
Instead of using store.select('appReducer').dispatch just use store.dispatch.

Why can't I import * these Javascript Files?

I'm trying to import these files inside the perimeters folder
basePerimeter.js
byePerimeter.js
secretPerimeter.js
my import code:
import * as perimeters from '../perimeters'
basePerimeter.js
import { Perimeter } from 'vue-kindergarten';
export default class BasePerimeter extends Perimeter {
isAdmin() {
return this.child && this.child.role === 'admin';
}
}
byePerimeter.js
import basePerimeter from './basePerimeter';
export default new basePerimeter({
purpose: 'bye',
govern: {
'can route': () => true,
'can viewParagraph': function () {
return this.isAdmin();
},
},
});
secretPerimeter.js
import basePerimeter from './basePerimeter';
export default new basePerimeter({
purpose: 'secret',
govern: {
'can route': function () {
return this.isAdmin();
},
},
});
but if I import it individually, it works.
Like this:
import basePerimeter from '../perimeters/basePerimeter'
I need to import via * because of this code:
router.beforeEach((to, from, next) => {
const perimeter = perimeters[`${to.name}Perimeter`];
if (perimeter) {
const sandbox = createSandbox(child(store), {
perimeters: [
perimeter,
],
});
if (!sandbox.isAllowed('route')) {
return next('/');
}
}
return next();
});
Why is it throwing this error:
ERROR in ./src/router/index.js
Module not found: Error: Can't resolve '../perimeters' in 'E:\my\vue\instance\src\router'
# ./src/router/index.js 13:0-44
# ./src/main.js
# multi ./build/dev-client ./src/main.js
I Don't know what's happening here but adding an index.js file and importing the files I needed solved my problem.
index.js
import byePerimeter from './byePerimeter'
import secretPerimeter from './secretPerimeter'
export {
byePerimeter,
secretPerimeter
}