typescript 元素访问表达式应该带一个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52368118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:39:27  来源:igfitidea点击:

An element access expression should take an argument

angulartypescript

提问by Hemant

I am new to Angular I have tried to create some sample application but getting error. Please help. I am trying to make my own from googles project (https://stackblitz.com/angular/ooqemvjyqkb?file=src%2Fapp%2Fheroes%2Fheroes.component.ts) When I remove array from "users = User[];" it works fine but it does not give a build([ts] Type 'User[]' is not assignable to type 'typeof User'.). With "users = User[];" it does not even compile(suggestion [ts] An element access expression should take an argument.(any)) .

我是 Angular 的新手,我尝试创建一些示例应用程序,但出现错误。请帮忙。我正在尝试从 googles 项目(https://stackblitz.com/angular/ooqemvjyqkb?file=src%2Fapp%2Fheroes%2Fheroes.component.ts)中创建自己的项目,当我从“users = User[];”中删除数组时 它工作正常,但它没有提供构建([ts] 类型 'User[]' 不可分配给类型 'typeof User'。)。随着“用户=用户[];” 它甚至不 compile(suggestion [ts] An element access expression should take an argument.(any)) 。

import { Component, OnInit } from '@angular/core';

import { User } from '../user';
import { UserService } from '../user.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  selectedUser: User;

  users = User[]; // review use of array type. users = User[];

  constructor(
    private userService: UserService
    ) { }

  ngOnInit() {
    this.getUsers();
  }

  onSelect(user: User): void {
    this.selectedUser = user;
  }

  getUsers(): void {
    this.userService.getUsers()
    .subscribe(users => this.users = users);
  }

    save(): void {
    this.userService.updateUser(this.users);
  }

  add(name: string): void {
    console.log(name);
    name = name.trim();
    if (!name) { return; }
    this.userService.addUser({ name } as User)
      .subscribe(user => {
        this.users.push(user);
      });
  }
}

////////////////////user.ts///////////////

///////////////////user.ts///////////////

export class User {
    id: number;
    name: string;
  }

///////////////user.service.ts////////////////

///////////////user.service.ts////////////////

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { User } from './user';
// import { USERS } from '../assets/data/userData';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({ providedIn: 'root' })

export class UserService {

  private usersUrl = 'api/users';

  constructor(
    private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    // return of(USERS);
    return this.http.get<User[]>(this.usersUrl);
  }

  /** GET user by id. Will 404 if id not found */
getUser(id: number): Observable<User> {
  const url = `${this.usersUrl}/${id}`;
  return this.http.get<User>(url);
}

/** PUT: update the user on the server */
updateUser (user: User): Observable<any> {
  return this.http.put(this.usersUrl, user, httpOptions);
}

/** POST: add a new user to the server */
addUser (user: User): Observable<User> {
  return this.http.post<User>(this.usersUrl, user, httpOptions);
}

/* GET users whose name contains search term */
searchUsers(term: string): Observable<User[]> {
  if (!term.trim()) {
    // if not search term, return empty hero array.
    return of([]);
  }
  return this.http.get<User[]>(`${this.usersUrl}/?name=${term}`);
}

}

回答by D1ZZYD 23

Replace

代替

users = User[];

with

user: User[]

That should do the trick.

这应该够了吧。

回答by Pipo

The correct syntax for me was not

对我来说正确的语法不是

user: User[] = User[] // WRONG SYNTAX

but

users: User[] = []

or

或者

users: User[] = new Array<User>()

回答by amracel

Try:

尝试:

    users = [Users];

I find that syntax tends to work better.

我发现语法往往效果更好。

回答by 4dc0

I just ran into this trying to compile a standalone typescript file with tsc. In my case I had to change this:

我刚刚在尝试使用 tsc 编译一个独立的打字稿文件时遇到了这个问题。就我而言,我不得不改变这一点:

users: User[];

to this:

对此:

let users: User[];

回答by Zubair A.

do not adding users = User[], as you are getting users from service. instead just declare the type like users: User[];

不要添加用户 = 用户 [],因为您是从服务中获取用户的。相反,只需声明类型,如 users: User[];

Above will work

以上将工作

回答by Moritz Lüdtke

As some people wrote before, you try to add User[]which is an array to a method that only needs one single user. You access one element of an arry, by writing the following code:

正如一些人之前写的那样,您尝试将User[]which 是一个数组添加到只需要一个用户的方法中。您可以通过编写以下代码访问 arry 的一个元素:

save(): void {
    this.userService.updateUser(this.users[THE_INDEX_FROM_THE_CURRENT_USER]);
}

That should only give one Userto the updateUser()

这应该只给一个UserupdateUser()

So in general:

所以一般来说:

oneArray: Foo[];         <-   creates an array named 'oneArray' with Foo objects inside
oneFoo = oneArray[0];    <-   Gives you the first element of the array