在angular2组件完成过程后呈现html

在angular2组件完成过程后呈现html

问题描述:

我在获取响应之后在我的应用程序组件中调用api,我可以决定要显示哪个div以及要隐藏哪个div。 但它在组件进程完成之前呈现html。 下面是代码示例。在angular2组件完成过程后呈现html

user.service.ts

import { Injectable } from '@angular/core'; 
import {Http,Headers, RequestOptions, Response, URLSearchParams} from '@angular/http'; 

@Injectable() 
export class UserService { 

    private static isUserLoggedIn: boolean = false; 
    private userData: any; 
    constructor(private http: Http) { } 

    public isLoggedIn() { 
    return UserService.isUserLoggedIn; 
    } 

    public getUserData() { 
    return this.userData; 
    } 

    setUserData() { 

    var url = 'http://api.example.in/user/logincheck'; 
    this.http 
     .get(url) 
     .map(response => response.json()) 
     .subscribe(
     (data) => { 
     this.userData = data; 
     if (typeof this.userData.id != 'undefined' && this.userData.id > 0) { 
      UserService.isUserLoggedIn = true; 
     } 
     }, 
     (err) => { throw err; } 
    ); 
    } 

} 

app.component.ts

import { Component, OnInit } from '@angular/core'; 
import { UserService } from './services/user/user.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    providers: [UserService], 
}) 
export class AppComponent { 
    constructor(private userService: UserService) { 
    this.userLoggedInCheck(); 
    } 

    ngOnInit() { 

    } 

    userLoggedInCheck() { 
    this.userService.setUserData(); 
    } 
} 

我想在这里完成后叫userLoggedInCheck功能的加载HTML。

返回真实值userLoggedInCheck如果满足必要的条件并将其分配给app.component.ts文件中的变量。在html文件中,根据函数的返回变量将内容放置在* ngIf内。

例如。

userLoggedInCheck() { 
    this.showHtml = this.userService.setUserData(); 
    } 

和HTML

<div *ngIf="showHtml"> 
    ....... // code 
</div> 
+0

我已经作出了服务,所以我想发出一个请求,只有1次时只有页面加载。如果我在每次点击其他路由时将它调用的头部组件中放入api调用,则我的html部分位于头部组件中。 –

+0

尝试使用服务文件作为共享文件(https://*.com/questions/40527284/pass-data-between-independent-components-in-angular-2),然后使用* ngIf控制html。 –