嗨,我有这个组件,我打电话给updateUserInfo'从一项服务,但我无法更改视图中的值,任何人都可以帮助我吗?
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css'],
});
export class MenuComponent {
firstname = "aaa";
constructor() { }
updateUserInfo(user){
this.firstname = "ciao";
}
}
答案 0 :(得分:0)
您必须在构造函数
中调用函数updateUserInfo答案 1 :(得分:0)
PowerRequestDisplayRequired
}
答案 2 :(得分: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));
}
答案 3 :(得分: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;
}