Angular 7 观察者未定义

Angular 7 Observer is not defined

我有一个服务,比如 MyService,其目的只是玩 rxjs observables:

import { Injectable } from '@angular/core'
import { Observable } from 'rxjs';

@Injectable()
export class MyService {

    private mydatas: any[] = [{
        id: 1,
        name: "My first"
      }, 
      {
        id: 2,
        name: "My second"
      },
      {
        id: 3,
        name: "My third"
      }];

        public getMys(): any {

            const myObservable = new Observable((observer) => {
                setTimeout(() => {
                    observer.next(this.mydatas);
                }, 1000);

                setTimeout(() => {
                    observer.error("I AM AN ERRROR!!!")
                }, 2000);

                setTimeout(() => {
                    observer.complete();
                }, 3000);

                return myObservable;
            });
        }
}

它被组件使用:

import { Component, OnInit } from '@angular/core';
import { MyService } from '../shared/my.service';

@Component({
  selector: 'my-list',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})

export class MyListComponent implements OnInit {

  mys: any[] = [];

  constructor(private myService: MyService) { }

  ngOnInit() {

    const myObservable = this.myService.getMys();

    myObservable.subscribe(
      (mys) => {
        this.mys = mys;
            },
      (err) => {
            },
      () => {
            }
    );
  }
}

我 运行 它在 html 里面,带有 angular 注释(*ngFor),当我 运行 它时,我在 Chrome的控制台:

ERROR TypeError: Cannot read property 'subscribe' of undefined at MyListComponent.push../src/app/my/my-list/my-list.component.ts.MyListComponent.ngOnInit

我做错了什么?

谢谢

你实际上必须 return 观察者,否则方法只是 returns undefined:

public getMys(): Observable<any[]> {
  return new Observable((
// ...

如果您正确地键入提示您的方法,错误会更清楚。

您正在 return观察者,return 分配可观察对象后的 myObservable。

           const myObservable = new Observable((observer) => {
            setTimeout(() => {
                observer.next(this.mydatas);
            }, 1000);

            setTimeout(() => {
                observer.error("I AM AN ERRROR!!!")
            }, 2000);

            setTimeout(() => {
                observer.complete();
            }, 3000);

        });

            return myObservable;