标签: angular6

使用参数动态创建组件

我有一个使用 ComponentFactoryResolver 动态创建的组件

this.container.clear();
let factory  = this.resolver.resolveComponentFactory(DynamicComponent);
this.componentRef = this.container.createComponent(factory);

template: '...<child-component [param1]="param1"></child-component>...';
Run Code Online (Sandbox Code Playgroud)

问题是 DynamicComponent 的模板有子组件和输入绑定。有没有办法在动态创建组件时将参数传递给子组件?

frontend angular angular6

6
推荐指数
2
解决办法
9991
查看次数

如何将本地库导入 Angular6 应用程序?

我正在构建一个应用程序,该应用程序将使用(很可能)其他应用程序也会使用的库。在 Angular 6 中,创建一个新库就像ng g library MyLibrary. 构建您的库,使其可在您的应用程序中使用ng build MyLibrary。最后,根据文档,您可以像import { SomethingFromMyLibrary } from 'MyLibrary';在 app.module.ts 文件中导入任何其他库一样导入您的库。我的问题是,为什么这对我不起作用?我收到错误Cannot find module 'AbsenceMonitorCore'对于我的情况,具体的导入语句是import { AbsenceMonitorCoreModule } from 'AbsenceMonitorCore';

这是我的库模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { AbsenceMonitorCoreComponent } from './absence-monitor-core.component';

import { AbsencesComponent } from './components/absences/absences.component';
import { SigninComponent } from './components/signin/signin.component';
import …
Run Code Online (Sandbox Code Playgroud)

angular angular6

6
推荐指数
1
解决办法
9245
查看次数

自定义 ValidatorFn - Angular 6

我想创建一个自定义通用验证器,它将通过参数传递正则表达式的模式和要检查的属性(表单组)的名称。我有以下代码

UserName: new FormControl('',
      [
        Validators.required,
        Validators.minLength(8),
        this.OnlyNumbersAndLetterValidator(/^[a-zA-Z0-9]+$/, "UserName")
      ]
    )

OnlyNumbersAndLetterValidator(regexPattern: RegExp, propertyName: string): ValidatorFn {
        return (currentControl: AbstractControl): { [key: string]: any } => {
          if (!regexPattern.test(currentControl.value)) {
            return { propertyName: true }
          }
        }
      }
Run Code Online (Sandbox Code Playgroud)

问题是当表达式无效时,返回"{propertyName: true}",而不是"{UserName: true}",有什么问题?

angular angular6

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

在 Angular 6 中使用 ng2-smart-table 创建服务器端分页

我正在尝试使用该组件<ng2-smart-table>。我确实做到了,但是我需要在用户单击页面或列进行排序后刷新数据,有什么方法可以捕获这些事件并刷新数据?

table.component.html

<ng2-smart-table 
[settings]="settings" 
[source]="characters">
</ng2-smart-table>
Run Code Online (Sandbox Code Playgroud)

表.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class TableService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getCharacters() {
    return this
            .http
            .get(`${this.url}/characters`);
  }
}
Run Code Online (Sandbox Code Playgroud)

表.interface.ts

export interface Table {
   ticket: String;
   title: String;
   state: String;
   owner: String;
   age: String;
   priority: String;
}
Run Code Online (Sandbox Code Playgroud)

table.component.ts

import { Component, OnInit } from '@angular/core';
import { TableService } from './table.service';
import { Table } from './table.interface'; …
Run Code Online (Sandbox Code Playgroud)

typescript ng2-smart-table angular angular6

6
推荐指数
1
解决办法
9919
查看次数

如何使用 Angular 6 在 Jasmine 中对 ngrx 功能选择器进行单元测试?

我的产品功能有一个功能选择器和相邻的选择器:

const getProductState = createFeatureSelector<fromProducts.State>('products');

export const getOldProducts = createSelector(
    getProductState,
    state => state.oldProducts
);

export getNewProducts = createSelector(
    getProductState,
    state => state.newProducts
);
Run Code Online (Sandbox Code Playgroud)

我想对这些选择器进行单元测试。我读过的大多数文章和帖子都只涉及非特征选择器,所以是时候模拟特征状态了,我的测试将返回undefined状态对象。我的规范文件如下所示:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [
            StoreModule.forRoot({}),
            StoreModule.forFeature('products', fromProduct.reducer)
        ],
        declarations: [],
        providers: [{
            provide: Store, useClass: class { select = jasmine.createSpy('select'); dispatch = jasmine.createSpy('dispatch'); }
        }]
    })
    mockStore = TestBed.get(Store);
}));

it('getOldProducts should return the oldProducts', () => {
    const state = {
        name: 'Product1',
        oldProduct: {
            price: 45.00
        }, …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine ngrx angular angular6

6
推荐指数
1
解决办法
4186
查看次数

SignalR SSE 握手失败

在“Windows Server 2008 R2”上以相同域名但不同端口(分别为:81 和:80)托管 ASP.Net Core 2.1 webapi 和 Angular 6 webapp;不包含在同一文件夹中。

根据这篇文章,当 Websockets 不可用时,SSE 是(标准)回退,这是预期的,因为服务器不支持 Websockets,因为它们是在 IIS 8.0 中引入的(服务器是 IIS 7.5)

在开发中一切正常。但是,发布后,浏览器控制台在 15 秒后报告以下内容(可疑的是默认的“HandshakeTimeout”时间)。

> Information: SSE connected to http://my.website.com:81/notify?id=kaSkcGUjcZD4ylJAC7B70A
> Error: Connection disconnected with error 'Error: Server returned handshake error: Handshake was canceled.'.
> Error: Not Found
Run Code Online (Sandbox Code Playgroud)

Startup.cs 当前设置如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddMemoryCache();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddCors(o => {
        o.AddPolicy("Limited", builder => builder
            .WithOrigins("http://my.website.com") // .AllowAnyOrigin() also tested and worked
            .AllowAnyMethod()
            .AllowAnyHeader() …
Run Code Online (Sandbox Code Playgroud)

windows-server-2008-r2 signalr asp.net-core-webapi angular6 asp.net-core-2.1

6
推荐指数
1
解决办法
2671
查看次数

嵌套在 ngIf 中时,异步管道订阅无法正常工作

我有一个快速搜索框,我想要一个加载动画。我用ng-templatewithngIf来显示/隐藏这个动画。我有一些 li 嵌套在同一个 div 中,它使用异步管道订阅搜索结果 Observable 以显示结果。当*ngIf父 div上没有时,这个异步管道工作得很好,但是当我申请时它似乎不再订阅了ngIf。这是预期的行为吗?还是我做错了什么?

我的标记看起来像这样。

<input #searchBox type="text" (keyup)="itemLoading=true;searchTerm$.next(searchBox.value)"/>
<div *ngIf="!itemLoading else loading">
<!--Remove ngIf then items will display correctly when search-->
<!-- <div> -->
  <ul>
    <li *ngFor="let item of result$ | async ">{{item}}</li>
  </ul>
</div>
<ng-template #loading>
  <p>LOADING...</p>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

我正在使用 switchMap 来运行搜索:

private source = of(['apple', 'pear', 'banana']).pipe(delay(500));

  searchTerm$ = new Subject<string>();
  result$: Observable<string[]>;
  itemLoading = false;  

  constructor() {
    this.result$ = this.searchTerm$.pipe(
      tap(term => console.log('search term captured: …
Run Code Online (Sandbox Code Playgroud)

javascript rxjs typescript angular angular6

6
推荐指数
1
解决办法
3654
查看次数

Angular 6 - 使用 http.get responseType 时出错:ResponseContentType.Blob

我想在(角度 5)中制作一个这样的可观察对象。如何responseType在 Angular 6 中声明?

Angular 5 代码:

public ExportSomeThing(
        ano: number
    ): Observable<IDownloadArquivo> {
        let q = this.http
            .get(this.apiUrl + ano + '/pordia/excel', {
                responseType: ResponseContentType.Blob  // <<<-- This code
            }).map((res) => { 
Run Code Online (Sandbox Code Playgroud)

我的角度 6 代码:

public MyExport(
    ano: number
  ): Observable<IXpto> {
    let q = this.http
      .get( this.api_rul + ano + '/some_path/', {
        responseType: "ResponseContentType.Blob"  // <<<--- error here !!!
      }).map((res) => {
Run Code Online (Sandbox Code Playgroud)

错误是:

[ts]
Argument of type '{ responseType: "ResponseContentType.Blob"; }' is not assignable to …
Run Code Online (Sandbox Code Playgroud)

response httpclient angular angular5 angular6

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

Angular6 - 使用 ngx-translate 使用 API 调用加载翻译到后端

我想在我的前端使用 ngx-translate 在应用程序加载时动态加载翻译。

我的后端以 JSON 格式返回响应,例如:

{
   "something: "something"
}
Run Code Online (Sandbox Code Playgroud)

我想在我的 TranslateLoader 上使用该输出而不是本地en.json文件。

有什么方法可以实现吗?

TL;DL:我想调用“ http://localhost:xxxx/api/translation/EN ”来获取翻译的 JSON 响应并将其加载TranslateHttpLoader

frontend typescript ngx-translate angular angular6

6
推荐指数
1
解决办法
7360
查看次数

在 Angular 6 库中使用 NgRx(带有 ngrx-actions 库)

我正在尝试将具有多个模块的 Angular 应用程序拆分为多个(单独的)Angular 库(使用本指南),因此我可以在多个 Angular 应用程序中使用这些库。
目前该项目有几个模块,例如:

  • 一个用于认证/授权;
  • 一个包含所有类型的表格组件
  • 一个包含所有类型的过滤器组件
  • 一个包含所有类型的图表组件
  • ......(我想你明白了)......

我开始致力于将身份验证/授权模块“转换”为库,因为我预计这将是最难和最复杂的模块。
现在我面临一些问题,我将在下面解释。

该模块(目前存在)结合使用 NgRx 和 ngrx-actions 来减少样板。就像(在指南中)提到的那样,创建了一个库和一个用于测试库的应用程序。我将现有模块的所有内容复制到库文件夹中。

必须进行一些调整,因为现有模块从 environment.ts 和 global.ts 读取一些常量,当它用作库时(可能)不存在。

现在我的文件夹结构如下所示,以提供更多上下文(删除了 node_modules):

.
??? README.md
??? angular.json
??? e2e
?   ??? protractor.conf.js
?   ??? src
?   ?   ??? app.e2e-spec.ts
?   ?   ??? app.po.ts
?   ??? tsconfig.e2e.json
??? package-lock.json
??? package.json
??? projects
?   ??? auth-lib
?   ?   ??? karma.conf.js
?   ?   ??? ng-package.json
?   ?   ??? ng-package.prod.json
?   ?   ??? package-lock.json
? …
Run Code Online (Sandbox Code Playgroud)

ngrx angular angular-library angular6

6
推荐指数
1
解决办法
4695
查看次数