首页 \ 问答 \ void不能分配给类型值User Angular 2(void is not assignable to type value User Angular 2)

void不能分配给类型值User Angular 2(void is not assignable to type value User Angular 2)

我使用rx / js Observable调用JSON文件。

服务

constructor(private http: Http){

}

 getUserById():Observable<User[]> {

let url = this.mockData;
let header = new Headers({'Content-Type': 'application/json'});

return this.http.get(url)
    .map((res:Response) =><User[]>res.json())
    .do(data => console.log("User Data: "+JSON.stringify(data)))
    .catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};

零件:

    @Input() users: User[] = [];

        userTemp: User[] = [];

getUserById(userId){

        this._searchService.getUserById()
            .filter(users => {
                for(let user of users){
                    if(user.userName === userId){
                        this.userTemp.push(user);
                    }}});

        return this.userTemp;

    }

under users => {当我将鼠标悬停在它上面时(Users: Users[]) => void is not assignable) => boolean.

我知道我遗漏了一个小细节,但我不知道它在哪里。 任何建议将不胜感激。

------------------------------ update 1 ------------------ --------现在尝试这个但是它编译但不起作用。

this._searchService.getUserById()
            ._do(users => {
                for(let user of this.users){
                    if(user.id == userId){
                        this.userTemp.push(user);
                    }
                }
            });

---------------------更新2 --------------------------我从下面的帖子中获得了一些建议,现在我试图像这样做,但它没有渲染,也没有给出任何错误。

在组件中:

@Input() users: IUser[] = [];

在组件中调用的方法:

case 'role':
          this.users = this.getUserByRole(this.role);
          console.log(this.role);
          break;

组件中的方法:

 getUserByRole(role){

        this._searchService.getUsers()
            .subscribe(users => {
                for(let user of users) {
                    if(user.role == role){
                        this.users.push(user);
                    }}});

        return this.users;
    }

服务方式:

getUsers(): Observable<IUser[]> {
        let users = this.http
            .get(this.url)
            .map(res => res.json());
        return users;
    }

在控制台中,它将打印输入框中的任何内容,并确认http调用的url是有效的。

我试图这样做,所以我需要做的就是改变http网址,以便稍后有一个真正的网址,而不必改变太多。

--------------更新3 ----------------------

在HTML中我有:

 <td>{{data.role | async}}</td>

组件中的方法:

getUserByRole(role){

        return this._searchService.getUsers()
            .map(data => {
                return data.filter((x:any) => x.role == role)
            });
    }

领域:

 @Input() users: Observable<IUser[]>;

调用方法:

case 'role':
         console.log(this.getUserByRole(this.role));
         this.users = this.getUserByRole(this.role);
         console.log(this.users);
         break;

错误:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

在我的searchService中,我现在正在考虑这样做,但仍然无法正常工作:

 findUserByRole(user: IUser) {
        return this.http.get(this.url)
            .map(res => res.json())
            .subscribe(
                data => {

                }
            );
    }

I am calling a JSON file using rx/js Observable.

Service

constructor(private http: Http){

}

 getUserById():Observable<User[]> {

let url = this.mockData;
let header = new Headers({'Content-Type': 'application/json'});

return this.http.get(url)
    .map((res:Response) =><User[]>res.json())
    .do(data => console.log("User Data: "+JSON.stringify(data)))
    .catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};

component:

    @Input() users: User[] = [];

        userTemp: User[] = [];

getUserById(userId){

        this._searchService.getUserById()
            .filter(users => {
                for(let user of users){
                    if(user.userName === userId){
                        this.userTemp.push(user);
                    }}});

        return this.userTemp;

    }

under users => { says when I hover over it (Users: Users[]) => void is not assignable) => boolean.

I know there is a small detail I am missing but I am not sure where it is. Any advice would be greatly appreciated.

------------------------------update 1-------------------------- Trying this now but and it compiles but doesn't work.

this._searchService.getUserById()
            ._do(users => {
                for(let user of this.users){
                    if(user.id == userId){
                        this.userTemp.push(user);
                    }
                }
            });

---------------------Update 2-------------------------- I got some advice from the posts below and now I am trying to do it like this, but it is rendering nothing and giving no errors.

In component:

@Input() users: IUser[] = [];

Method being called in component:

case 'role':
          this.users = this.getUserByRole(this.role);
          console.log(this.role);
          break;

method in component:

 getUserByRole(role){

        this._searchService.getUsers()
            .subscribe(users => {
                for(let user of users) {
                    if(user.role == role){
                        this.users.push(user);
                    }}});

        return this.users;
    }

Service method:

getUsers(): Observable<IUser[]> {
        let users = this.http
            .get(this.url)
            .map(res => res.json());
        return users;
    }

In the console it will print whatever I put in the input box and I confirmed the url for the http call is valid.

I am trying to do it like this so all I need to do is change the http url to have headers and a real url later without have to change to much.

--------------Update 3----------------------

In the HTML I have:

 <td>{{data.role | async}}</td>

method in component:

getUserByRole(role){

        return this._searchService.getUsers()
            .map(data => {
                return data.filter((x:any) => x.role == role)
            });
    }

Field:

 @Input() users: Observable<IUser[]>;

Calling the method:

case 'role':
         console.log(this.getUserByRole(this.role));
         this.users = this.getUserByRole(this.role);
         console.log(this.users);
         break;

error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

In my searchService I am now looking at doing it this way but still not working:

 findUserByRole(user: IUser) {
        return this.http.get(this.url)
            .map(res => res.json())
            .subscribe(
                data => {

                }
            );
    }

原文:https://stackoverflow.com/questions/43076243
更新时间:2023-02-19 13:02

最满意答案

GraphQLNonNull类型包装用于将字段和参数指定为非null。 对于字段,这意味着查询结果中字段的值不能为空。 对于参数,这意味着该参数不能被忽略或具有空值。 所以你的代码只需要看起来更像这样:

args: {
  name: {
    type: new GraphQLNonNull(GraphQLString),
  },
  school: {
    type: new GraphQLNonNull(GraphQLString),
  },
},

The GraphQLNonNull type wrapper is used to specify both fields and arguments as non-null. For fields, that means the value of the field in the query results cannot be null. For arguments, that means that the argument cannot be left out or have a value of null. So your code just needs to look more like this:

args: {
  name: {
    type: new GraphQLNonNull(GraphQLString),
  },
  school: {
    type: new GraphQLNonNull(GraphQLString),
  },
},

相关问答

更多
  • 你可能正在寻找 canvas.Canvas.__init__(self, page1, *args, **kwargs) You're probably looking for canvas.Canvas.__init__(self, page1, *args, **kwargs)
  • 在Relay中查询连接字段时,您可以指定除first , last , before和after的标准分页参数之外的参数。 在上面的TodoMVC示例中,我们通过当前过滤器对状态进行限定。 您已经显示的TodoMVC代码的含义是,突变应该为过滤"active"或"any" (或默认状态)状态的查询添加新todo,但不会过滤仅过滤状态的查询"completed" (在上下文中有意义,因为突变增加了一个新的,活跃的待办事项)。 When you query for a connection field in R ...
  • GraphQLNonNull类型包装用于将字段和参数指定为非null。 对于字段,这意味着查询结果中字段的值不能为空。 对于参数,这意味着该参数不能被忽略或具有空值。 所以你的代码只需要看起来更像这样: args: { name: { type: new GraphQLNonNull(GraphQLString), }, school: { type: new GraphQLNonNull(GraphQLString), }, }, The GraphQLNonNull t ...
  • 您所看到的行为并非特定于GraphQL,而是一般的节点。 您的模块中存在循环依赖关系,这会导致user_type.js的require语句解析为company_type.js的不完整副本。 根据文档 ,给出了两个相互要求的模块( a.js和b.js ): 当main.js加载a.js , a.js依次加载b.js 此时, b.js尝试加载a.js 为了防止无限循环, a.js导出对象的未完成副本将返回到b.js模块。 然后b.js完成加载,并将其exports对象提供给a.js模块。 在导出定义中移动req ...
  • 根据你的Mongo Schema定义,我会说你对引用的理解是正确的,通过使用Schema.Types.ObjectId你是如何正确使用文档引用的。 现在,您GraphQLID将GraphQLID映射为GraphQLID的GraphQL 类型即可 。 我喜欢用这个别名,因为MongoId有两个原因。 1)因此,我明确知道,仅从GraphQL类型定义中可以看出,如果我忘记数据类型Schema.Types.ObjectId分配了什么,那么无需返回到Mongo模式就可以期待什么行为: Schema.Types.Ob ...
  • 你的增变器在你的模型上。 而您正在使用ValidatesRequests控制器特征来验证您的请求输入数据。 所以你的mutators只有在你运行你的验证之后才会被调用。 因此,我看到你有两个选择。 一个。 修改您的HTML以确保您始终收到布尔值。 例如,使用具有默认值的隐藏输入。 如果未选中该复选框,则只会提交此值。 ...
  • 当您为解析器返回的对象中的某个属性返回函数时会发生这种情况 - GraphQL将调用函数来解析该值,但它只会用三个参数而不是四个参数(参数,上下文和信息)调用它。 在这种情况下,父项或“根”值被删除,因为在这种情况下函数被作为解决这个相同的根值的一部分被调用。 要访问根值, childWithArg字段的解析器应该放在Parent类型的解析器下,如下所示: const resolvers = { Query: { parentWithArg(obj, args, ctx) { ...
  • 让我们回顾一下基本知识:“Accessor”和“Mutator”只是一个吸气者和二传手的奇特名字。 getter,“Accessor”,返回一个类的变量或其值。 一个setter,“Mutator”,设置一个类变量指针或它的值。 所以首先你需要设置一个包含一些变量的类来获取/设置: public class IDCard { private String mName; private String mFileName; private int mID; } 但是哦,不! 如果你实 ...
  • 您可以使用**kwargs代替,它允许任意关键字参数。 这应该比清除每个功能更容易。 你只需修改你的代码中的generate_outputs()方法: def generate_output(self, **kwargs): return self.method(self.ts, kwargs) 通过此修改,您可以调用generate_outputs() ,如下所示: x.generate_outputs(time_series, window ='1D', max_lag=25, use_pro ...
  • 看起来你缺少用户的args,因此,它应该如下所示: var users = new graphql.GraphQLObjectType({ name : 'user', description : 'this is user info', fields : function(){ return { id :{ type : graphql.GraphQLInt, resolve(user){ return user.id; ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)