2017-06-21 57 views
0

您好我有這個組件,我從服務調用'updateUserInfo',但我無法改變視圖中的值誰能幫助我嗎?model angular 4,從更新的模型改變視圖

@Component({ 
    selector: 'app-menu', 
    templateUrl: './menu.component.html', 
    styleUrls: ['./menu.component.css'], 

}); 

export class MenuComponent { 

    firstname = "aaa"; 

    constructor() { } 

    updateUserInfo(user){ 
     this.firstname = "ciao"; 

    } 
} 
+0

那麼你的HTML是什麼樣子? – LLai

+0

{{firstname}}

回答

0

例如yoг有user.service.ts

import {Injectable} from '@angular/core'; 
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/observable/throw'; 

@Injectable() 
export class UserService { 


    constructor(private http: Http) { 
    } 

getUserName() { 
    let headers = new Headers(); 
    headers.append('X-Requested-With', 'XMLHttpRequest'); 
    headers.append('Content-Type', 'application/json;'); 
    return this.http.get("http://YourUrl",{ headers: headers}) 
         .map((response: Response) =>response.json()) 
    } 
} 

這是您的組件:

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

@Component({ 
selector: 'app-menu', 
templateUrl: './menu.component.html', 
styleUrls: ['./menu.component.css'], 
providers: [UserService] 
}) 

export class MenuComponent { 

firstname = "aaa"; 

constructor(private userService: UserService) { 
////dont use in constructor many codes, best of use in ngOnInit 
} 

ngOnInit() { 
     this.userService.getUserName() 
     .subscribe(response=> {this.updateUserInfo(response.user.name);}); 
} 

updateUserInfo(user){ 
    this.firstname = user; 
} 
+0

感謝很多aimprogram我真的很喜歡你的幫助 –

+0

我很高興我可以幫你。 – aimprogman

0

你必須調用你的函數updateUserInfo在構造

+0

的問題是,我有一個叫updateUserInfo功能 –

+0

@GiovanniPolì必須在組件使用者地位,並在認購調用updateUserInfo() – aimprogman

+0

@GiovanniPolì如果你不能做到這一個服務,我可以顯示 – aimprogman

0
@Component({ 
    selector: 'app-menu', 
    templateUrl: './menu.component.html', 
    styleUrls: ['./menu.component.css'], 
    }) 

export class MenuComponent { 

firstname = "aaa"; 

constructor() { 
    this.updateUserInfo("text"); ///here called function 
} 

updateUserInfo(user){ 
    this.firstname = "ciao"; 
} 

}

0

如果控制器內的函數,該函數應該從組件內部調用,例如:

<div class="profile-usertitle-name"> {{ firstname }} </div> 
<button (click)="updateUserInfo('Mario')">Change name</button> 

如果您打電話給服務,服務應該有一個「承諾「(可能是一種可觀察的),你認同這一點。就像這樣:

constructor(private myService : MyService) { 
    myService.load().subscribe((user) => updateUserInfo(user)); 
} 
+0

問題是我有一個服務調用updateUserInfo函數 –

+0

但是,如果您必須從服務調用它在組件內部的方法'.updateUserInfo()',那麼這是錯誤的。通常你應該在組件中注入服務,而不是相反。也許這是更多的架構錯誤,你可能不會使用這些作品 –