2017-09-16 27 views
0

我在獲取響應之後在我的應用程序組件中調用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。

回答

0

返回真實值userLoggedInCheck如果滿足必要的條件並將其分配給app.component.ts文件中的變量。在html文件中,根據函數的返回變量將內容放置在* ngIf內。

例如。

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

和HTML

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

我已經作出了服務,所以我想發出一個請求,只有1次時只有頁面加載。如果我在每次點擊其他路由時將它調用的頭部組件中放入api調用,則我的html部分位於頭部組件中。 –

+0

嘗試使用服務文件作爲共享文件(https://stackoverflow.com/questions/40527284/pass-data-between-independent-components-in-angular-2),然後使用* ngIf控制html。 –

相關問題