自定义过滤器在Angular Hybrid应用中不起作用 [英] Custom filter not working in Angular Hybrid app

查看:94
本文介绍了自定义过滤器在Angular Hybrid应用中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将AngularJS 1.6应用程序与Angular 5一起转换为混合应用程序.我定义了以下简单过滤器:

I am attempting to convert an AngularJS 1.6 app in to a hybrid app along with Angular 5. I have the following simple filter defined:

(function () {
    "use strict";
    var filterId = "colorPicker";

    angular
        .module('app')
        .filter('colorPicker', colorPicker);

    function colorPicker() {
        return function (input) {
            var colorCode = '#2980b9';
            switch (input) {
                case 1:
                    colorCode = '#16a085';
                    break;
                case 2:
                    colorCode = '#a38761';
                    break;
                case 3:
                    colorCode = '#8e44ad';
                    break;
                case 4:
                    colorCode = '#ffa800';
                    break;
                case 5:
                    colorCode = '#d95459';
                    break;
                case 6:
                    colorCode = '#8eb021';
                    break;
                default:
            }
            return colorCode;
        };
    }
})();

过滤器的用法如下:ng-attr-style="background-color: {{ $index | colorPicker }}"

这在AngularJS应用程序中有效,但是在混合应用程序中出现以下错误:angular.js:14525 Error: [$injector:unpr] Unknown provider: colorPickerFilterProvider <- colorPickerFilter

This works in the AngularJS app, but I get the following error in the Hybrid app: angular.js:14525 Error: [$injector:unpr] Unknown provider: colorPickerFilterProvider <- colorPickerFilter

与以前一样,从AngularJS代码中调用过滤器.实际上,我几乎没有任何Angular 5代码.我只是想让现有代码按原样运行,但是要在Hybrid应用程序中运行.我不应该像以前那样使用过滤器吗?

The filter is called from the AngularJS code as it has before. In fact, I barely have any Angular 5 code. I'm just trying to get the existing code to run as it has been, but within the Hybrid app. Shouldn't I be able to use filters as before?

更新

我认为这可能与我遇到的有关控制器的其他错误有关:

I think this might be related to other errors I'm getting about controllers:

[$controller:ctrlreg] The controller with the name 'myController' is not registered.

我可以看到脚本文件下载成功,并且当我的app.module.ts引导AngularJS时没有抛出任何错误.实际上,我可以确定AngularJS正在运行,因为它收到有关未注入globalVars的错误(这是在我不再使用的剃刀视图中定义的),但是在我重新创建它后该错误消失了在TypeScript中进行降级",以便AngularJS可以使用它.

I can see the script files downloading successfully and no errors are being thrown when my app.module.ts bootstraps AngularJS. In fact, I'm somewhat certain that AngularJS is running since it was getting an error about globalVars not being injected (this was being defined in a razor view that I am no longer using) but the error went away after I recreated it in TypeScript and "downgraded" it so AngularJS could use it.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { downgradeInjectable, UpgradeModule } from '@angular/upgrade/static';

import { AppComponent } from './app.component';
import { GlobalVarsService } from './core/global-vars.service';

declare var angular: any;

angular.module('app', []).factory('globalVars', downgradeInjectable(GlobalVarsService));

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    UpgradeModule
  ],
  providers: [
    GlobalVarsService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private upgrade: UpgradeModule) {
    this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
  }
}

因此文件正在下载并执行,但是应用程序未找到控制器和过滤器(也许还有其他项目).我将所有旧代码放在名为"old"的文件夹中,然后更新了.angular-cli.json,以便在构建时将这些文件复制到输出中,以便可以通过index.html中的<script>标记来引用它们.这应该工作,不是吗?还是出于某种原因需要将文件与Angular 5捆绑在一起?

So the files are downloading and executing, but the controllers and filter (and maybe other items) are not found by the app. I put all the old code in a folder named "old" and then updated .angular-cli.json to copy these files to the output upon build so that I can reference them via <script> tags in the index.html. This should work, shouldn't it? Or do the files need to be bundled with the Angular 5 files for some reason?

// .angular-cli.json section
  "assets": [
    "assets",
    { "glob": "**/*", "input": "../old/app/", "output": "./app/" },
    { "glob": "**/*", "input": "../old/Content/", "output": "./Content/" },
    { "glob": "**/*", "input": "../old/Scripts/", "output": "./Scripts/" },
    "favicon.ico"
  ], 

推荐答案

发现了问题.实际上,我认为有两个问题.其中之一是,我认为我在降级globalVars服务降级时使用方括号来重新定义应用".

Found the problem. Actually I think there were two problems. One was that I think I was redefining "app" by including square brackets when downgrading my globalVars service.

angular.module('app', []).factory('globalVars', downgradeInjectable(GlobalVarsService));

代替

angular.module('app').factory('globalVars', downgradeInjectable(GlobalVarsService));

我认为另一个问题是鸡和蛋的问题.我的globalVars已被注入到AngularJS应用程序的配置函数中,但我认为可能需要降级globalVars的应用程序-仍不确定.对我来说幸运的是,我的app.js中没有引用globalVars的东西,因此我可以删除引用.

The other issue I think was a chicken-and-the-egg kind of problem. My globalVars was being injected into my AngularJS app's config function, but I think the app might have been needed to downgrade globalVars - still not completely sure. Luckily for me, nothing was referencing globalVars in my app.js so I was able to remove the reference.

这是我的app.module.ts的版本,终于可以正常工作了.我希望这对其他人有帮助!

This is the version of my app.module.ts that finally got it working. I hope this helps someone else!

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import { downgradeInjectable, UpgradeModule } from '@angular/upgrade/static';
import { environment } from '../environments/environment';

import { AppComponent } from './app.component';
import { GlobalVarsService } from './core/global-vars.service';

declare var angular: any;

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    UpgradeModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: OnAppInit,
      multi: true,
      deps: [GlobalVarsService, HttpClient]
    },
    GlobalVarsService
  ]
})
export class AppModule {
  constructor(private upgrade: UpgradeModule, private http: HttpClient) { }
  ngDoBootstrap() {
    angular.module('app').factory('globalVars', downgradeInjectable(GlobalVarsService));
    this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
  }
}

export function OnAppInit(globalVars: GlobalVarsService, http: HttpClient) {
  return (): Promise<any> => {
    return new Promise((resolve, reject) => {
      // Fetch data from the server before initializing the app.
      http.get(environment.apiBase + '/api/meta/data').subscribe(x => {
        globalVars.MetaData = x;
        globalVars.VersionNumber = globalVars.MetaData.versionNumber;
        globalVars.IsDebugBuild = globalVars.MetaData.isDebugBuild;
        globalVars.AuthorizedFeatures = globalVars.MetaData.authorizedFeatures;
        globalVars.User = globalVars.MetaData.user;
        resolve();
      });
    });
  };
}

这篇关于自定义过滤器在Angular Hybrid应用中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆