小编cal*_*r47的帖子

如何在Vuex 2中设置初始状态?

我正在为一个小应用程序使用Vue.js 2.0和Vuex 2.0.我正在通过调用从API检索初始状态的操作初始化根Vue实例上的'created'生命周期钩子中的存储....就像在我的根组件中一样:

const app = new Vue({
 el: "#app",
 router,
 store,
 data: {
     vacation: {},
 },
 components: {
    'vacation-status': VacationStatus,
 },
 created(){
    //initialize store data structure by submitting action.
    this.$store.dispatch('getVacation');
 },
 computed: {
 },
 methods: {
 }
});
Run Code Online (Sandbox Code Playgroud)

这工作得很好.这是我在这里打电话给我的商店的行动:

getVacation({commit}){
  api.getVacation().then(vacation => commit(UPDATE_VACATION, vacation))
}
Run Code Online (Sandbox Code Playgroud)

这与'UPDATE_VACATION'提交的变异在这里:

[UPDATE_VACATION] (state, payload) {
  state.vacation = payload.vacation;
},
Run Code Online (Sandbox Code Playgroud)

我的问题:当我加载应用程序时,所有从商店"获取"值的组件会抛出错误,我试图访问商店中的"未定义"值.换句话说,状态尚未初始化.

例如,我有一个组件在子组件中具有getter,如下所示:

computed: {
        arrival () {
            return this.$store.getters.arrival
        },
        departure() {
            return this.$store.getters.departure
        },
        countdown: function() {
            return this.$store.getters.countdown …
Run Code Online (Sandbox Code Playgroud)

vue.js vuex vuejs2

43
推荐指数
1
解决办法
4万
查看次数

webpack 构建后,bundle.js 中未定义导出的函数

我有由 Webpack 管理的构建过程。它将我的所有文件捆绑在一起并生成一个bundle.js文件。很典型的图案。

但是,当我将该文件包含bundle.js在网页中时,导出的默认函数未定义。为什么我不能从网页上的全局范围访问导出的函数?

这是我的 webpack 配置:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    entry: './src/js/index.js',
    output: {
        path: path.resolve('dist'),
        filename: 'bundle.js',
    },
    performance: {
        hints: false,
    },
    resolve: {
        modules: ['node_modules', path.join(__dirname, 'src'), 'assets'],
    },
    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                use: 'file-loader',
            },
        ],
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: `bundle.css`, …
Run Code Online (Sandbox Code Playgroud)

javascript webpack

11
推荐指数
1
解决办法
3532
查看次数

如何在 Angular 中使用第三方库动态创建组件?

使用角度 10

\n

SO 上有很多与此类似的问题,但我还没有找到一个可以回答我的情况的问题。

\n

我希望有人能指导我。

\n

我正在使用第三方库来显示 360\xc2\xb0 照片。这个第三方库有一个内置的API来显示场景中的热点。只需向库提供您想要成为热点的元素,它就会处理其余的事情。

\n

我的大部分内容都按预期工作,但有一些部分没有按预期工作。

\n

到目前为止,我正在动态生成我的组件,如下所示:

\n
this._hotspotFactory = this.resolver.resolveComponentFactory(HotspotComponent);\nconst component = this._hotspotFactory.create(this.injector);\n\n//Hydrate component with  bunch of data\ncomponent.instance.id = data.id;\n...\n\n// Create the Hotspot with Third Party\n// Calling this third party method injects the native element into the DOM. \n// Passing the nativeElement in. Looks great at first glance. \nconst hotspot = this._scene.createHotspot(data, component.location.nativeElement);\n\nthis.appRef.attachView(component.hostView);\ncomponent.hostView.detectChanges();\n\nif(component.instance.over.observers.length) {\n  hotspot.on(\'over\', (evt) => {\n    this.zone.run(() => {\n      component.instance.over.emit(evt);\n    });\n  });\n}\n\nif(component.instance.out.observers.length) {\n  hotspot.on(\'out\', (evt) => {\n    this.zone.run(() => …
Run Code Online (Sandbox Code Playgroud)

javascript angular angular-changedetection

9
推荐指数
1
解决办法
866
查看次数

在 Nodejs 中将回调转换为 RX.Observable

我正在开发一个使用无法换出的第三方库的项目。它本质上是指向 URL 源并返回数据。它返回承诺。它将返回的数据传递回匿名回调......不是你传递给函数的一个。

文档参差不齐,但这是他们指导您使用他们的库的方式。

third-party(URLsource, selector, scope)(function(err, data){ /* work with data array here*/ });
Run Code Online (Sandbox Code Playgroud)

目前,代码一团糟。这部分是为了回调地狱和过度使用承诺。

通过 observables 传输数据将有助于简化和清理这个项目......但我仍在学习 RXjs 以及 observables 是如何工作的。

我认为这个问题将是一个很好的候选者:

let datapull = Rx.Observable.bindNodeCallback(third-party);
let result = datapull(URLsource, selector, scope);
result.subscribe(result => console.log(result), e => console.log("Error: " + e)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,因为最后一个参数是:

third-party(URLsource, selector, scope)
Run Code Online (Sandbox Code Playgroud)

不是回调函数。

如何将此第三方函数的结果包装在 RX Observable 中?

node.js rxjs

5
推荐指数
1
解决办法
1729
查看次数

如何使用distinctUntilKeyChanged比较多个键?

我仍在学习 rxjs,并且我对如何为运算符 uniqueUntilChanged 编写自定义比较函数有点困惑。

我研究了使用distinctUntilKeyChanged,它对于单个键非常有用......但我有两个需要比较的键。

看来我可能需要合并扫描运算符来将发出的当前值与发出的最后一个值进行比较......?

好的,这是我的代码。我正在从谷歌地图流式传输地图中心更改。我不需要非常精确的地图中心地理位置,因此我对谷歌地图返回的大部分小数进行四舍五入。

searchStream$
  .map((value)=>{
  return {
    lat: round(value[1].lat, 1),
    lng: round(value[1].lng, 1)
  }
}).distinctUntilKeyChanged('lat')
  .do((position)=>{console.log(position)})
  .subscribe((position)=>{ this._store.dispatch(new QueryUpdateGeoPositionAPIAction({latitude: position.lat, longitude: position.lng})) });
Run Code Online (Sandbox Code Playgroud)

回到我的问题,如何比较两个属性(纬度和经度)以确保它仅在其中一个值发生变化时才发出值?

谢谢您的帮助!

javascript rxjs

5
推荐指数
1
解决办法
7597
查看次数

如何提高建议者的结果,但不使用弹性搜索进行过滤?

我正在使用弹性搜索 5.6。

我正在使用完成建议器在搜索字段中返回结果。我已成功映射和索引我的文档。我也得到了接近预期结果的结果。

在文档中,提到可以实现上下文来提升和/或过滤这里看到的结果:

完成建议器会考虑索引中的所有文档,但通常需要提供由某些标准过滤和/或提升的建议。

然而,我的问题是,我只收到过滤的结果......而不是简单的提升结果。如果我正确阅读文档,我应该能够在不过滤的情况下进行提升。文档

这个问题在一个简单的例子中很明显。假设搜索查询是“波特兰”。用户是密西根州波特兰市,因此我希望将该结果提高到比俄勒冈州波特兰市更高的结果。但是,目前我的上下文正在过滤结果,因此返回的不是 Portland, MEPortland, OR,而是返回 Portland, ME,因为它位于上下文区域内。

映射:

{
    "mappings": {
        "destination" : {
            "_all": {"enabled": false},
            "properties" :  {
                "name": {
                    "type": "text"
                },
                "suggest": {
                    "type": "completion",
                    "analyzer": "simple",
                    "contexts": {
                        "name": "location",
                        "type": "geo",
                        "path": "location"
                    }
                },
                "type": {
                    "type" : "keyword"
                },
                "state": {
                    "type" : "keyword"
                },
                "location": {
                    "type": "geo_point",
                    "index": true
                },
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例索引文档:

{
  "name": "Portland",
  "location": [ …
Run Code Online (Sandbox Code Playgroud)

elasticsearch

5
推荐指数
0
解决办法
329
查看次数

有没有什么时候我不需要在组件中处理取消订阅的例子?

我已经习惯于取消订阅我在组件中初始化的订阅。推荐的方法是takeUntil像这样使用运算符:

killSubscriptions: new Subject<any> = new Subject();

ngOnInit(){
   observableThing().pipe(takeUntil(this.killSubscriptions)).subscribe()
}

ngOnDestroy(){
  this.killSubscriptions.next();
  this.killSubscriptions.complete();
}
Run Code Online (Sandbox Code Playgroud)

但是前几天我正在使用覆盖和门户服务实现一个自定义对话框,并且我在Angular Material Library中的一个方法中间遇到了这个代码块

// When the dialog backdrop is clicked, we want to close it.
if (config.hasBackdrop) {
  overlayRef.backdropClick().subscribe(() => {
    if (!dialogRef.disableClose) {
      dialogRef.close();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

这个订阅是如何清理的?我唯一的猜测是在overlayRef处理时,订阅被清理。但是如何?

还有其他时候我们不需要处理取消订阅吗?

rxjs angular-material2 angular

4
推荐指数
1
解决办法
699
查看次数

Google Cloud Install上的Python错误.如何正确设置环境变量?

我正在尝试在我的Windows计算机上安装Google Cloud SDK .我目前在这台机器上安装了Python 2.7,它位于系统变量路径中,就像这样 - >C:\Python27\;

我在安装过程中收到此错误:

错误:gcloud无法加载:DLL加载失败:%1不是有效的Win32应用程序.

该错误消息还提示我检查Python可执行文件,说:

如果不是,请将CLOUDSDK_PYTHON环境变量设置为指向可用的Python 2.7可执行文件.

所以,我正在尝试在install.sh shell脚本中设置CLOUDSDK_PYTHON环境变量......但没有任何工作.这是该文件的代码:

echo Welcome to the Google Cloud SDK!

if [ -z "$CLOUDSDK_PYTHON" ]; then
 if [ -z "$(which python)" ]; then
  echo
  echo "To use the Google Cloud SDK, you must have Python installed and on your PATH."
  echo "As an alternative, you may also set the CLOUDSDK_PYTHON environment variable"
  echo "to the location of your Python executable."
  exit 1
 fi
 CLOUDSDK_PYTHON="python"
fi
Run Code Online (Sandbox Code Playgroud)

我尝试过 …

python google-app-engine python-2.7

3
推荐指数
3
解决办法
8616
查看次数

如何使用 jest 监视第三方功能?

我在嘲笑第三方依赖时遇到困难。我总是收到这个错误:

无法监视未定义的属性,因为它不是函数;未定义给定代替

以下是这个问题的详细信息。首先,这是我正在测试的功能:

文件:src/js/mp_wrapper.js

import { Viewer } from 'third-party';

module.exports = {
    createViewer: container => {
        if (util.isElement(container)) {
            return new Viewer(container);
        } else {
            throw new Error(
                'Invalid Element when attempting to create underlying viewer.',
            );
        }
    },
}
Run Code Online (Sandbox Code Playgroud)

查看我的第三方源代码,Viewer非常简单,如下所示:


function Viewer(){
 // Doing things
}

Viewer.prototype.foo = function(){

}

module.exports = Viewer;
Run Code Online (Sandbox Code Playgroud)

最后,这是我的测试。

文件:/tests/mp_wrapper.spec.js


import { Viewer } from 'third-party`;
import mp_wrapper from '../src/js/mp_wrapper';

describe('mp_wrapper', () => {
    describe('createViewer', () => {
        test('returns …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jestjs

3
推荐指数
1
解决办法
1万
查看次数

如何使用angular调用canActivate中的异步方法?

我正在尝试在Angular 4.2.4中为管理路由实现canActivate防护.

基于这个堆栈问题:canActivate Question,我想我正在做的一切正确.但是,唉,我似乎无法让事情发挥作用.

这是模块保护:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private _store: Store<AppState>,
              private router: Router,
              private czauth: CzauthService) { }

  canActivate(route: ActivatedRouteSnapshot):Observable<boolean>{
    return this.czauth.verifyAdminUser().first();
  }
};
Run Code Online (Sandbox Code Playgroud)

这是我的czauth服务:

  getToken():Observable<firebase.User>{
    return this.af.idToken;
  }

  verifyUserRole(token){
      this.token = token;
      console.log(token);// Log out "PromiseObservable {_isScalar: false, promise: D, scheduler: undefined}"
      let headers = new Headers({ 'Authorization': 'Bearer ' + token});
      let options = new RequestOptions({ headers: headers });
      return this.http.get(environment.api+'/verifyadminuser', options).map((response)=>{return response.json()});
  }


  verifyAdminUser():Observable<boolean>{
    return this.getToken()
      .map((user)=>{return Observable.fromPromise(user.getIdToken())})
      .map((token)=>{return this.verifyUserRole(token)}) …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous rxjs angular

0
推荐指数
1
解决办法
2457
查看次数