简体   繁体   English

Angular 5订阅不是一个功能

[英]Angular 5 Subscribe not a function

Angular return a error : Error: Uncaught (in promise): TypeError: res.users.subscribe is not a function. Angular返回错误:错误:未捕获(在promise中):TypeError:res.users.subscribe不是函数。

Since this morning, I don't understand what's wrong in my resolve. 从今天早上起,我不明白我的决心是什么错。

UserService.ts UserService.ts

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

@Injectable()
export class UsersService {

    private api = 'http://localhost:3000/users';
    private headers = new HttpHeaders();

    constructor(
        private http: HttpClient
    ) {}

     getAllUsers(): Observable<any[]> {
         return this.http.get<any[]>(this.api, {headers: this.headers, responseType: 'json' });
    }
}

UserResolve.ts: UserResolve.ts:

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { UsersService } from '../services/users.service';

@Injectable()
export class UsersResolve implements Resolve<any> {

    constructor(private usersService: UsersService) {}

    resolve() {
       return this.usersService.getAllUsers();
    }
}

UserComponent.ts UserComponent.ts

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

import {Users} from '../_shared/models/Users';

@Component({
  selector: 'app-user',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.sass']
})

export class UsersComponent implements OnInit {

    constructor(private route: ActivatedRoute) {}

    public title: string;
    public users: Users[] = [];

    ngOnInit() {
        this.route.data.forEach((res: any): any => {
           this.title = res.title;
           res.users.subscribe(users =>  {
              console.log(users);
              this.users = users;
           });
        });
    }
}

When I log res.users, it return "function UsersResolve()" with not proto subscribe... 当我记录res.users时,它返回“function UsersResolve()”而不是proto订阅...

The json is Array of Object like : json是Object of Object,如:

{
  id: 13246,
  guid: '46ffgd456dfs',
  name: 'John Doe',
  adress: ...
}

Can the problem come from the contents of my json ? 问题可能来自我的json的内容吗?

Originally, I wanted to train on the RxJS operator... 最初,我想训练RxJS操作员......

You're applying subscribe on Array. 您正在对Array应用subscribe。 You should do it on Observable. 你应该在Observable上做。

Try to apply below changes.. You can perform operations on data once you understand it's value on console. 尝试应用以下更改。一旦您了解数据在控制台上的价值,您就可以对数据执行操作。

UserComponent.ts UserComponent.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {Users} from '../_shared/models/Users';

@Component({
  selector: 'app-user',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.sass']
})

export class UsersComponent implements OnInit {

    constructor(private route: ActivatedRoute) {}

    public title: string;
    public users: Users[] = [];

    ngOnInit() {
        this.route.data.subscribe(data => console.log(data));
    }
}

UPDATE UPDATE

As mentioned in Comments: 如评论中所述:

if you've defined routes like this: 如果你已经定义了这样的路线:

const appRoutes: Routes = 
[ ... 
 { path: 'users',
   component: UsersComponent,
   resolve: { 
     users : UsersResolve 
   } 
 } 
];

The you should be able to get the data as: 你应该能够得到如下数据:

ngOnInit() {
        this.route.data.subscribe(data => console.log(data['users']));
    }

From de angular.io doc: 来自de angular.io doc:

interface ActivatedRoute {
  snapshot: ActivatedRouteSnapshot
  url: Observable<UrlSegment[]>
  params: Observable<Params>
  queryParams: Observable<Params>
  fragment: Observable<string>
  data: Observable<Data>
  outlet: string
  component: Type<any> | string | null
  get routeConfig: Route | null
  get root: ActivatedRoute
  get parent: ActivatedRoute | null
  get firstChild: ActivatedRoute | null
  get children: ActivatedRoute[]
  get pathFromRoot: ActivatedRoute[]
  get paramMap: Observable<ParamMap>
  get queryParamMap: Observable<ParamMap>
  toString(): string
}

That data is the observable himself. 这些数据本身就是可观察的。 Try: 尝试:

this.route.data.subscribe(data =>  {
      console.log(data);
   });
});

Remember, subscribe is the ear to an observable voice. 请记住,订阅是听到可观察声音的耳朵。

you can access the resolved data in two ways 您可以通过两种方式访问​​已解析的数据

ActivatedRoute data Property which holds the static and resolved data of the current route ActivatedRoute data保存当前路由的静态和已解析数据的属性
ActivatedRouteSnapshot : the no-observable alternative. ActivatedRouteSnapshot :无法观察的替代方案。

you need to add resolve property to the route configuration, which is an object where each key points to a resolver. 您需要将resolve属性添加到路由配置,该配置是每个键指向解析程序的对象。

    const appRoutes: Routes = [{ path: 'users', component: UsersComponent, 
         data: { title : 'Liste des Utilisateurs'},
          resolve:{ users : UsersResolve } } 
]

Approach-1 方法1

 ngOnInit() {
        this.route.data.subscribe(value=>{

   this.title=value.title;
    this.users=value.user;
});

    }

Approach:2 做法:2

ngOnInit() {

       this.title=this.route.snapshot.data.title;
        this.users=this.route.data.snapshot.user;


        }

STACKBLITZ DEMO

The above answers are right on, but I ran into a special case of this. 上面的答案是正确的,但我遇到了一个特例。

The method being called was an observable and was used in other parts of the application as an observable, yet when I ran it, it was saying the dreaded subscribe is not a function . 被调用的方法是一个可观察的方法,并在应用程序的其他部分用作可观察的方法,但是当我运行它时,它说可怕的subscribe is not a function

The issue was, I was running in Jasmine unit tests, I had defined a custom mock, and that mock was not returning an observable. 问题是,我在Jasmine单元测试中运行,我已经定义了一个自定义模拟,并且该模拟没有返回一个可观察的。 In such cases it is easy to goof up the mock and return a different type then the actual function being mocked returns. 在这种情况下,很容易搞砸模拟并返回不同的类型然后被模拟的实际函数返回。 Correcting my mock fixed my issue. 纠正我的模拟修复我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM