我有2个组件和1个服务文件, 有一个登录组件和一个仪表板组件。
这是我的登录组件,它订阅了服务文件中的http请求。当我控制台日志this.userService.user
时,它会正确返回。当我路由到dashboard
并将this.userService.user
记录在仪表板组件中时,它是未定义的。
import { Component, OnInit } from "@angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { UserService } from "../../shared/services.module";
@Component({
selector: "login",
moduleId: module.id,
templateUrl: "./login.component.html",
styleUrls: ["./login.css"],
})
export class LoginComponent implements OnInit {
email: string;
password: string;
constructor(private router: RouterExtensions, private userService: UserService) { }
signUp() {
this.userService.login(this.email, this.password)
.subscribe(res => {
console.log(this.userService.user)
this.router.navigate(["/dashboard"], { clearHistory: true, animated: false });
});
}
ngOnInit(): void {
}
}
这是我的仪表板组件,当我登录this.userService.user
时未定义。
import { Component, OnInit, Input } from "@angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { UserService } from "../../shared/services.module";
@Component({
selector: "dashboard",
moduleId: module.id,
templateUrl: "./dashboard.component.html",
styleUrls: ["./dashboard.css"],
})
export class DashboardComponent implements OnInit {
constructor(private router: RouterExtensions, private userService: UserService) {
}
ngOnInit(): void {
console.log(this.userService.user)
console.log(this.userService.getUserName())
}
}
这是我的服务文件
import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Config } from "../config";
import { catchError } from 'rxjs/operators';
import { map, delay, retryWhen, take } from 'rxjs/operators';
import { HttpErrorHandler, HandleError } from '../../http-error-handler.service';
import { User } from '../../models/user/user'
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
@Injectable()
export class UserService {
user: any;
private handleError: HandleError;
constructor(private http: HttpClient, httpErrorHandler: HttpErrorHandler) {
this.handleError = httpErrorHandler.createHandleError('HeroesService');
}
getUserName() {
console.log("return name");
console.log(this.user)
if (!this.user) {
return "failed";
}
console.log(this.user.name)
return this.user.name
}
login(email, password) {
let data = JSON.stringify({'email': email,'password': password})
return this.http.post(Config.userUrl + 'login', data, httpOptions)
.map((res: any) => {
let u = res.user
this.user = new User(u.name, u.email)
console.log(this.user)
return res
})
.pipe(
catchError(this.handleError('login', null))
);
}
}
奇怪的是,当我什至使用getUserName
之类的辅助函数来返回名称时,即使在服务文件中,该名称仍未定义。
有人知道为什么它返回未定义的吗?任何帮助将不胜感激。 谢谢
答案 0 :(得分:2)
尝试一下:
您在哪里提供服务的模块
@NgModule({
imports: [
...
],
declarations: [
...
],
providers: [
... // You have propably there the service that you want to provide globally, remove it
]
})
export class YourModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: YourModule, // name of this module
providers: [ YourService ] // put there the service, that you want to provide globally
};
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
...
YourModule.forRoot() // add this
],
providers: [
...
],
bootstrap: [
AppComponent
]
})
export class AppModule {
}
您要在全球范围内提供的服务
@Injectable() // remove the "providedIn: ..." if you have it there
export class YourService {
...
}
组件
@Component({
selector: "dashboard",
moduleId: module.id, // remove this line
templateUrl: "./dashboard.component.html",
styleUrls: ["./dashboard.css"],
})
export class DashboardComponent implements OnInit {
...
}
也不要忘记将YourModule
导入到要使用imports
的模块的YourService
中。
答案 1 :(得分:1)
我想当你这样声明
@Injectable({providedIn:'root'})
它可用于整个应用程序