小编Ang*_*ant的帖子

手动设置表格到无效的角度2+

有没有办法手动将formGroup设置为无效状态?

myForm.invalid = true;也试过了myForm.status = 'INVALID'

但是invalid,statusconst.

我不想将特定控件标记为无效.但整个形式.

angular angular-forms

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

在react jest中测试文件上传

我有类似的代码(仅保留相关代码)

function App() {
  const [values, setValues] = useState([]);

  async function onUpload(event) {
    if (event?.target.files?.length) {
      const data = await event.target.files[0].text();
      const json = JSON.parse(data);
      setValues(json);
    } else {
      throw new Error('couldnt get files');
    }
  }

  return (
    <div>
      {Boolean(!values.length) && (
        <input data-testid="upInput" accept="application/JSON" type="file" onChange={onUpload} />
      )}
      {Boolean(values.length) && (
        <div data-testid="handler">
          <ValuesHandler values={values} />
        </div>
      )}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

现在我想测试values用户上传文件时设置是否正确,然后ValuesHandler显示在页面中。

我正在我的 App.test.tsx 中朝这个方向尝试

import user from '@testing-library/user-event';
import someValues from '../somefile.json';
import { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library react-hooks

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

异步管道不适用于主题

我在服务中有以下 BehaviorSubject:

  isAuthenticated = new BehaviorSubject<boolean>(false);
Run Code Online (Sandbox Code Playgroud)

我在组件中按如下方式使用它:

  authenticated: Observable<boolean>;

  constructor(private accountService: AccountService) { }

  ngOnInit() {
    this.authenticated = this.accountService.isAuthenticated.asObservable();
  }
Run Code Online (Sandbox Code Playgroud)

在模板中,我执行以下操作:

  <li class="login-button" *ngIf="!authenticated | async">
    <a (click)="authenticate()">Log in</a>
  </li>
  <li *ngIf="authenticated | async">
    <a>Logged in</a>
  </li>
Run Code Online (Sandbox Code Playgroud)

问题是我没有看到这两个中的任何一个li,尽管假设第一个应该出现,因为我将 Subject 的初始值分配给 false。

我究竟做错了什么?

rxjs subject-observer angular

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

lerna 未在包中生成 node_module

我有一个带有 Lerna 的 monorepo 和具有基本结构的 typescript

- root 
  package.json
  - packages
      package-A
         package.json
         src
      package-B
         package.json
         src
Run Code Online (Sandbox Code Playgroud)

根package.json tsconfig配置

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "sourceMap": true,
    "allowSyntheticDefaultImports": true,
    "paths": {
      "@namespace/*": [
        "packages/*/src"
      ]
    },
    "esModuleInterop": true,
    "skipLibCheck": true,
    "types": [],
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}
Run Code Online (Sandbox Code Playgroud)

每个包的 tsconfig 看起来像

{
  "extends": "../../tsconfig.json",
  "include": ["src/**/*.ts"],
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "baseUrl": "."
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我运行时lerna bootstraplerna boostrap --hoist包 …

npm typescript package.json lerna monorepo

6
推荐指数
0
解决办法
1123
查看次数

等待 Promise.all 中的 array.map 迭代

我有以下代码,应该为客户添加项目(如果它们尚不存在)。执行应该是并行的。

await Promise.all(
    customers.map(async (customer) => {
        return customer.items.map(async (item) => {
            return new Promise(async (resolve) => {
                const productExists = someArray.some(
                    (arrayValue) => arrayValue === item.id
                );
                if (!productExists) {
                    logger.info(
                    `customer item ${item.id} does not exist, creating...`
                    );
                    await createCustomerItem(item.id);
                    logger.info(`customer item ${item.id} created.`);

                    someArray.push(item.id);
                } else {
                    logger.info(`customer item ${item.id} already exists, skipping...`);
                }
                resolve(true);
            });
        });
    })

);

logger.info(`All items should now be present`);
Run Code Online (Sandbox Code Playgroud)

问题是createCustomerItem在以下情况下执行不会等待解决!productExists)

这是日志

customer item 32310 does not exist, creating... …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous node.js promise

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

与 Commander 的嵌套命令

我有以下代码

export const program = new Command();

program.version('0.0.1');

program
  .command('groups')
  .command('create')
  .action(() => console.log('creating'))
  .command('delete')
  .action(() => console.log('deleting-all'))

program.parse(process.argv)
Run Code Online (Sandbox Code Playgroud)

我想要实现的目标是

groups creategroups delete

然而,删除的代码链接到创建。它识别groups createand groups create delete(我不想要)但不识别groups delete

javascript node.js node-commander

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

在 React 中使用上下文在兄弟姐妹之间传递上下文

我有以下代码,我尝试使用contextapi 从一个组件获取其同级组件的值。

import React from "react";
import ReactDOM from "react-dom";

function App() {
  return (
    <div>
      <TheButton />
      <Display />
    </div>
  );
}

export const NumberContext = React.createContext();

function TheButton() {
  return (
    <NumberContext.Provider value={"test"}>
      <button>Click me</button>
    </NumberContext.Provider>
  );
}

function Display() {
  const context = React.useContext(NumberContext);
  return <div>The answer {context}.</div>;
}

ReactDOM.render(<App />, document.querySelector("#root"));
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我正在提供程序中传递“测试”值,但是当页面呈现时,我看到的只是“答案”。

这是针对该问题的 Codesandbox https://codesandbox.io/s/pedantic-forest-zjlc2

reactjs react-hooks

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

Rxjs iif 或简单 if

我有以下代码:

obs.pipe(
   switchMap((val) => {
       // some logic...
       return iif(() => condition, someObservable())
   })
);
Run Code Online (Sandbox Code Playgroud)

我只是想知道为什么不能通过简单的而不是实现这if一点iif

 if (condition) {
    return someObservable();
 }
Run Code Online (Sandbox Code Playgroud)

javascript rxjs

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

在玩笑中模拟特定的配置值

我有以下 default/config.js 文件

/* eslint-disable @typescript-eslint/no-var-requires */
require('dotenv').config({
  path: require('find-config')('.env'),
});

module.exports = {
  cronInterval: process.env.CRON_INTERVAL,
  queueName: process.env.QUEUE_NAME || '',
  isVisible: process.env.IS_VISIBLE
};
Run Code Online (Sandbox Code Playgroud)

在我的 index.ts 中,我有

import config from 'config';
import * as cron from 'node-cron';

const isVisible = config.get<boolean>('isVisible');
const queueName = config.get<string>('queueName');
const cronInterval = config.get<string>('cronInterval');

function startProcess(queueName) {
    cron.schedule(cronInterval, () => {});
}

// process starts here
if (isVisible) {
  startProcess(queueName);
} else {
  logger.info('Wont start')
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我想测试 的两种情况isVisible,同时保持其他配置值不变。

我试过

describe.only('isVisible', () => {
    beforeEach(() …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing node.js jestjs node-config

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

在for循环中以角度2链接http调用

我有一些看起来像的代码

//service.ts

addProduct(productId) {
   this.http.post('someUrl', ReqData).map(json).subscribe(doStuff);
}

//component.ts

addAllproducts(productsIds) {
   productIds.forEach(productId => service.addProduct(productId);
}
Run Code Online (Sandbox Code Playgroud)

我想要的是能够在调用下一个productId之前等待每个调用完成,而不使用window.setTimeout..

javascript typescript ngrx angular

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