Angular"无法读取未定义的属性'订阅'

Mer*_*kos 16 typescript angular

在我开始提问之前,我想告诉你我已经做了大量的研究,但是我找不到解决方案(解释)为什么会出现这个错误.

还请注意,我是Angular的新手,我刚开始学习它是如何工作的.

所以,我遇到的问题是我在这个问题的标题中输入的内容.

我尝试做的是根据我在Udemy上购买的课程,使用Firebase构建登录系统.

我使用的代码如下:

auth.service.ts

import {Injectable} from '@angular/core';
import * as firebase from 'firebase';

@Injectable ()
export class AuthService {
    token: string;

    // ...

    singInUser ( email: string, password: string ) {
        // login process here ...
    }

    // Responsible to retrieve the authenticated user token
    getToken () {   
        return firebase
            .auth ()
            .currentUser
            .getIdToken ();
    }
}
Run Code Online (Sandbox Code Playgroud)

数据storage.service.ts

// ... Dependencies here
@Injectable ()
export class DataStorageService {
    private recipeEndPoint: string = 'https://my-unique-id.firebaseio.com/recipes.json';
    private recipeSubscription: Observable<any> = new Observable();

    constructor ( private http: Http,
                  private recipes: RecipeService,
                  private authService: AuthService ) {}

    // other functionality ...

    getRecipes () {
        const token = this.authService.getToken ();

        token.then (
            ( token: string ) => {
                this.recipeSubscription = this.http.get ( this.recipeEndPoint + '?auth=' + token ).map (
                    ( data: Response ) => {
                        return data.json ();
                    }
                );

                // THIS PARTICULAR CODE WORKS AS EXPECTED
                // WITH NO ISSUES
                this.recipeSubscription.subscribe (
                    ( data: Response ) => {
                        console.log ( 'Data response: ', data );
                    },
                    ( error ) => {
                        console.log ( 'Error: ' + error );
                    }
                )
            }
        );

        // This is supposed to return an Observable to the caller
        return this.recipeSubscription;
    }
}
Run Code Online (Sandbox Code Playgroud)

header.component.ts

// Dependencies here ...

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  constructor(private dataStorage: DataStorageService, private recipeService: RecipeService) { }

  // Other Code Here ...

  onFetchData() {
    let recipeSubscription = this.dataStorage.getRecipes();

    // THIS RETURNS TRUE
    console.log(recipeSubscription instanceof Observable);

    // THIS LINE THEN RETURNS THE MESSAGE:
    // ERROR TypeError: Cannot read property 'subscribe' of undefined
    recipeSubscription.subscribe();

    // IF I COMMENT OUT THE PREVIOUS LINE
    setTimeout(
      () => {
        // THIS RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      500
    );

    setTimeout(
      () => {
        // AS WELL THIS ONE RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      1000
    );

    setTimeout(
      () => {
        // AS WELL THIS ONE RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      1500
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

所以,不幸的是,我看不出这段代码会出现什么问题.谁能发现我做错了什么?

注意: 我删除了部分代码只是为了使代码段更具可读性.如果您需要任何其他部分,请随时问我,我会在这里提供.

更新#1

这就是它的样子 header.component.html

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">Logo Here</div>

        <div class="navbar-default">
            <ul class="nav navbar-nav">
                <!-- Left Navigation Options -->
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <!-- Right Navigation Options -->
                <li class="dropdown" appDropdown>
                    <a routerLink="/" class="dropdown-toggle" role="button">Manage <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li>
                            <a style="cursor: pointer;" (click)="onSaveData()">Save Data</a>
                        </li>
                        <li>
                            <!-- Here is where I call the onFetchData method -->
                            <a style="cursor: pointer;" (click)="onFetchData()">Fetch Data</a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>
Run Code Online (Sandbox Code Playgroud)

小智 28

使用unitialized EventEmitter我得到了同样的错误:

@Output() change: EventEmitter<any>;
Run Code Online (Sandbox Code Playgroud)

代替:

@Output() change: EventEmitter<any> = new EventEmitter<any>();
Run Code Online (Sandbox Code Playgroud)

尝试订阅更改事件的更高级别组件中发生错误.


Ang*_*hef 16

问题似乎是代码执行的顺序,更具体地说是getRecipes()方法:

// Numbers indicate the execution order

getRecipes () {
    const token = this.authService.getToken ();

    // 1. You call a promise, which will take a while to execute...
    token.then (
        ( token: string ) => {
            // 3. Finally, this bit gets executed, but only when the promise resolves.
            this.recipeSubscription = ...
        }
    );

    // 2. Then, you return a variable that hasn't been assigned yet,
    // due to the async nature of the promise.
    return this.recipeSubscription;
}
Run Code Online (Sandbox Code Playgroud)

解决getRecipes ()方法是你的方法不应该订阅.它应该返回Promise或Observable.

像这样的东西:

getRecipes() {
    // Convert the initial promise into an observable
    // so can you use operators like map(), mergeMap()... to transform it.
    const tokenObs = Observable.fromPromise(this.authService.getToken());

    // Merge the token observable into an HTTP observable
    // and return the JSON data from the response.
    return tokenObs
      .mergeMap(token => this.http.get('XXX?auth=' + token))
      .map(resp => resp.json());
}
Run Code Online (Sandbox Code Playgroud)

然后,调用代码HeaderComponent变为:

const recipeObs = this.dataStorage.getRecipes();
recipesObs.subcribe(jsonData => {
  // Use the JSON data from the HTTP response
});
Run Code Online (Sandbox Code Playgroud)

几点评论:

  • 您需要显式导入代码中使用的RxJS运算符.如果您按照我的示例,则需要在开头添加以下导入:
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
Run Code Online (Sandbox Code Playgroud)
  • 你永远不应该订阅创建observable的方法.在您的情况下,请不要订阅getRecipes().总是在最后一分钟订阅.您可以多次订阅同一个observable,但要注意每个订阅重新执行observable(在http请求的情况下,它意味着您多次运行请求;不理想......).
  • 调用变量不是一个好主意,recipeSubscription因为它包含一个Observable而不是一个变量Subscription.订阅是subscribe()返回的.换句话说:const subscription = observable.subscribe().
  • 我发现您直接使用了Firebase SDK.你知道AngularFire库吗?


小智 6

问题是,您返回一个可观察值并在 Token() 的响应中重新分配它。

尝试为你现在拥有的可观察对象创建一个主题,我发现这些更容易使用。

public recipeSubscription: Subject<any> = new Subject();
Run Code Online (Sandbox Code Playgroud)

将您的任务更改为

this.recipeSubscription = this.http.get....
Run Code Online (Sandbox Code Playgroud)

let response = this.http.get....
Run Code Online (Sandbox Code Playgroud)

在被调用的函数中订阅它:

response.subscribe((res) => {this.recipeSubscription.next(res)})
Run Code Online (Sandbox Code Playgroud)

现在您可以直接在房产上订阅

this.dataStorage.recipeSubscription.subscribe((res) => {
    // Do stuff.
});

this.dataStorage.getRecipes();
Run Code Online (Sandbox Code Playgroud)

我希望这足以帮助你:)


Art*_*lva 5

问题

我偶然发现了相同的错误,原因是我正在@OutputngOnInit()中初始化事件发射器。

export class MyClass implements OnInit {

    @Output()
    onChange : EventEmitter<void>;

    ngOnInit() {
        // DO NOT initialize @Output event here
        this.onChange = new EventEmitter<void>();    
    }
}
Run Code Online (Sandbox Code Playgroud)

当我将初始化更改为声明的相同位置时,它起作用了。

export class MyClass implements OnInit {

    @Output()
    onChange : EventEmitter<void> = new EventEmitter<void>();

    ngOnInit() {
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为这是因为父组件尝试过早地订阅事件(在ngOnInit()触发之前)。