如何从父组件通信到子组件

如何从父组件通信到子组件

本文介绍了Angular2:如何从父组件通信到子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在标签之间加载了一些 div.如下.

I'm loading some of div in between tag. Its as bellow.

这是我的 index.html

Here is my index.html

<html>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>

<!-- 3. Display the application -->

<body>
<my-app>Loading...</my-app>
</body>
</html>

app.module.ts

@NgModule({
imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
],
declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent,
    NewsfeedComponent,
    TopBarComponent,
    SideMenuComponent
],
providers : [
    AuthGaurd
],
bootstrap: [
    AppComponent
] })
export class AppComponent {}

home.component.ts

home.component.ts

@Component({
    selector: 'home',
    moduleId: module.id,
    templateUrl: 'home.component.html',
    providers : [
        LoginService
    ]
})

export class HomeComponent implements OnInit{
isLoggedin : boolean;
constructor (private loginService : LoginService) { }
ngOnInit(): void {
    this.loginService.getLogged().subscribe((isLoggedIn: boolean) => {
        this.isLoggedin = isLoggedIn;
    }); }
}

home.component.html

<side-menu *ngIf='isLoggedin'></side-menu>
<top-bar *ngIf='isLoggedin'></top-bar>
<router-outlet></router-outlet>

auth.gaurd.ts

auth.gaurd.ts

@Injectable()
export class AuthGaurd implements CanActivate{
    constructor(private router : Router) {
    }
    canActivate(){
        if (localStorage.getItem('isLogin')){
            return true;
        }
        this.router.navigate(['/login'])
        return false;
    }
}

login.service.ts

@Injectable()
export class LoginService {
    private subject: Subject<boolean> = new Subject<boolean>();
    constructor(private router : Router) {
    }
    login(){
        this.setLogged(true);
        localStorage.setItem("isLogin","true");
        this.router.navigate(['/news-feed']);
    }
    logout(){
        this.setLogged(false);
        localStorage.removeItem("isLogin");
        this.router.navigate(['/login']);
    }
    getLogged(): Observable<boolean> {
        return this.subject.asObservable();
    }
    setLogged(val : boolean): void {
        this.subject.next(val);
    }
}

login.component.ts

@Component({
    selector: 'login',
    moduleId: module.id,
    templateUrl: 'login.component.html'
})

export class LoginComponent {
    constructor (private loginService : LoginService) {
    }

    login(){
        this.loginService.login()
    }
}

login.component.html

<input type="number" #mobileNumber />
<input type="password" #password />
<input type="button" (click)="login()">

newsfeed.component.ts

@Component({
    selector: 'newsfeed',
    moduleId: module.id,
    templateUrl: 'newsfeed.component.html',
})

export class NewsfeedComponent {

}

newsfeed.component.html

一些 html 文本....!!!!

some html text....!!!!

app-routing.module.ts

app-routing.module.ts

@NgModule({
imports: [
    RouterModule.forRoot([
        {
            path : 'login',
            component : LoginComponent
        },
        {
            path : 'news-feed',
            component : NewsfeedComponent,
            canActivate : [AuthGaurd]
        },
        {
            path : '',
            redirectTo : '/news-feed',
            pathMatch : 'full'
        }
        {
            path: '**',
            component: LoginComponent
        }
    ])
],
exports: [
    RouterModule
]
})
export class AppRoutingModule {}

实际上,当我点击时它工作正常.就像它的启动一样完美,而不是点击登录按钮,它会转发到新闻源并显示预期的结果.但是当我从浏览器 url 开始时,它没有从 home.html 加载侧栏和顶栏组件

Actually it's working fine when i'm going with clicks. like its launching perfect than on click of login button it forwards to newsfeed and shows the expected result. but when I'm going from the browser url, its not loading side bar and top bar component from the home.html

推荐答案

我不确定这是否能解决所有问题,但我认为您想先从 localstorage 读取值以获取最近存储的状态,如果您使用 this.subject.emit() 在订阅者订阅之前被调用,>BehaviorSubject 侦听器也会获得最后的状态.

I'm not sure if this fixes everything but I think you want to read the value from localstorage first to get the recently stored status and if you use BehaviorSubject listeners also get the last status if this.subject.emit() was called before a subscriber was subscribing.

@Injectable()
export class LoginService {
    //private subject: Subject<boolean> = new Subject<boolean>(false);
    private subject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(); // <<< changed
    constructor(private router : Router) {
      this.sublect.next(logalStorage.getItem('isLogin')); // <<< added
    }
    login(){
        this.setLogged(true);
        localStorage.setItem("isLogin","true");
        this.router.navigate(['/news-feed']);
    }
    logout(){
        this.setLogged(false);
        localStorage.removeItem("isLogin");
        this.router.navigate(['/login']);
    }
    getLogged(): Observable<boolean> {
        return this.subject.asObservable();
    }
    setLogged(val : boolean): void {
        this.subject.next(val);
    }
}

这篇关于Angular2:如何从父组件通信到子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:34