问题
My app.component
contains the <nav>
of the website, which uses [routerLink]
to go to the different pages. It imports each of the pages' components. One of the pages is a login page. If the user is not logged in, I want the navigation to say Login- if the user is, Logout.
In app.component
:
my_userO : userO = undefined;
constructor (private my_userS:userS){
my_userS.userChanged.suscribe(temp => this.updateNav());
updateNav(){
this.my_userO = this.my_userS.getUser();
}
logOut(){
this.my_userS.setUser(undefined);
}
and in its template:
<li><a *ngIf="!my_userO" [routerLink]="['LoginPage']">Login</a></li>
<li><a *ngIf="my_userO" [routerLink]="['HomePage']"(click)="logOut()">Logout</a></li>
userS
is a global service (it is bootstrapped in main.ts
and not added as a provider in any of the components I am using it in) I have that looks like this:
public userChanged: EventEmitter<{}>
currentUser : userO = undefined;
constructor(private http:Http){
this.userChanged = new EventEmitter();
}
getLogin(username: string, password: string): Promise<userO>{
return this.http.get(this.getLoginUrl+username).toPromise().then(response => response.json().data).catch(this.handleError);
}
getUser(){
return this.currentUser;
}
setUser(x_userO: userO){
this.currentUser = x_userO;
this.userChanged.emit(undefined);
}
In the login page, I just run getLogin
then setUser
with what the former returned.
My problem is that I get the error "Property suscribe does not exist on type EventEmitter<{}>".
回答1:
Its a typo
Use subscribe
, not suscribe
I don't have enough reputation to answer Colum below but that's totally incorrect.
emit()
returns voidEventEmitter
extends (inherits)Subject
which is an observable and an observer.export declare class EventEmitter<T> extends Subject<T>
an EventEmitter
is an rxjs Subject with some modifications, most notably it does not use next() to send a value down the stream but uses emit().
It also allows setting an async logic where the emit will be async.
回答2:
using vscode, auto complete added this line:
import { EventEmitter } from 'events';
i had to change it to the following to resolve this.:
import { EventEmitter } from '@angular/core';
回答3:
It doesn't have a subscribe method as it does not return an observable.
The emit()
method of EventEmitter
does however return an observable so you need to create an input which is connected to the event that is emitted.
You can then subscribe to this.
Take a look at this: http://www.syntaxsuccess.com/viewarticle/unit-testing-eventemitter-in-angular-2.0
回答4:
check for the import of EventEmitter
it should be import { EventEmitter } from '@angular/core';
来源:https://stackoverflow.com/questions/38249155/angular2-subscribe-property-on-eventemitter-not-existing