简体   繁体   中英

subscribe angular2 not working

I must be missing something very obvious, but I'm having problems using subscribe on a component to listen a change in a service.

I have a login component(not posted here) which calls the login method in the LoginService, the navbar component should listen when a user login.

What am I missing?

My Service:

@Injectable()
export class LoginService {
    private request = new Request();
    private sessionData:BehaviorSubject<any> = new BehaviorSubject([])
    public session:Observable<any>

    constructor(private http: Http, _router: Router) {
        console.log("Login Service created.", http);
        this.session = this.sessionData.asObservable()
    }

    public getSessionData(): Observable<any>{
        return this.sessionData.asObservable();
    }

    login(userCredentials:UserCredentials):Observable<any> {    
        console.log("requesting login")
        this.request.ServiceType = "Connect"
        this.request.SessionId = "sessionlessrequest"
        this.request.Compression = "no"
        this.request.Parameters = userCredentials;
        let jsonrequest = JSON.stringify(this.request)
        return this.http.post("http://localhost/request.php", "data="+ jsonrequest,
            { headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
            })
        }).map( (responseData) => {
            this.sessionData = responseData.json();
            this.sessionData.next;
            this.sessionData.share;
            this.session = responseData.json();
            console.log(this.sessionData)
            return null
        })
    }

Then there is my component:

@Component({
    selector: 'navbar',
    templateUrl: './app/navbar/navbar.component.html',
    providers: [SessionService, LoginService, UserCredentials]
})

export class NavBarComponent {
    sessionData: any
    constructor(sessionService: SessionService, private loginService: LoginService, private userCredentials: UserCredentials) {
    }

    ngOninit() {
        this.loginService.getSessionData().subscribe((value => {
            this.sessionData = value;
            console.log(this.sessionData)
        }))
    }

Gunter thank you for your help

Update after Günter's answer:

app.module.ts

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent,
        AboutComponent,
        NavBarComponent,
        LoginComponent,

    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        JsonpModule,
        routing,

    ],
    providers: [appRoutingProviders, LoginService ],
    bootstrap: [AppComponent]
})

LoginComponent.ts:

@Component({
    selector: 'login',
    templateUrl: './app/login/login.component.html',
    providers: []
})

    export class LoginComponent {
        public usercredentials = new UserCredentials();
        constructor(private loginService:LoginService) {

        }
        login() {
            console.log(this.usercredentials)
            this.loginService.login(this.usercredentials).subscribe()
        }
    }

LoginService.ts:

@Injectable()
export class LoginService {
    private request = new Request();
    private sessionData:BehaviorSubject<any> = new BehaviorSubject([])
    public session:Observable<any>
    constructor(private http: Http, _router: Router) {
        console.log("Login Service created.", http);
        this.session = this.sessionData.asObservable()
    }

    public getSessionData(): Observable<any>{
        return this.sessionData.asObservable();
    }

    login(userCredentials:UserCredentials):Observable<any> {    
        console.log("requesting login")
        this.request.ServiceType = "Connect"
        this.request.SessionId = "sessionlessrequest"
        this.request.Compression = "no"
        this.request.Parameters = userCredentials;
        let jsonrequest = JSON.stringify(this.request)
        return this.http.post("http://localhost/request.php", "data="+ jsonrequest,
            { headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
            })
        }).map( (responseData) => {
            this.sessionData = responseData.json();
            this.sessionData.next;
            this.sessionData.share;
            this.session = responseData.json();
            console.log(this.sessionData)
            return null
        })
}

navbar component.ts :

@Component({
    selector: 'navbar',
    templateUrl: './app/navbar/navbar.component.html',
    providers: []
})

export class NavBarComponent {
    sessionData: any
    constructor(private loginService: LoginService) {

    }

    ngOninit() {
        this.loginService.getSessionData().subscribe((value => {
            this.sessionData = value;
            console.log(this.sessionData)
        }))
    }

I see in my debugger that I get only 1 instance of loginservice, however it still doesn't work.

If you want to share a service with other components or services in your application, don't provide it everywhere where you use it.

Where you want to use it you add it as constructor parameter.

To define where a single instance should be shared in your application, decide where to put it as provider. Angular2 DI maintains a single instance per provider.

If you add SessionService , LoginService , and UserCredentials on every component, every component will get a different instance. When you add it to @NgModule() then one instance will be shared with your entire application:

@NgModule({
  providers: [SessionService, LoginService, UserCredentials]
})
class AppModule {}
@Component({
    selector: 'navbar',
    templateUrl: './app/navbar/navbar.component.html',
    providers: []
})

update

this.sessionData.next; doesn't do anything. It should be this.sessionData.next(someValue) .

Also this.sessionData.share; should be this.session = this.sessionData.asObservable().share()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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