如何在AngularJS CLI中的HTML上显示Ajax加载的图像

时间:2018-08-30 21:16:38

标签: angularjs typescript angular-cli-v6

我正在使用angular6。我已加载用户json数据,我想显示个人资料图片,但显示为空。如何解决此问题

userprofile.component.js

GroupBox

} }

userprofile.component.html

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

@Component({
  selector: 'app-sidenav',
  templateUrl: './userprofile.component.html',
  styleUrls: ['./userprofile.component.scss'],
  providers: [UserService]
})
export class SidenavComponent implements OnInit {
  public $auth: User; 
  constructor(public _user: UserService) {}

  ngOnInit() {
   this._user.authUser().subscribe(
      result => {
        this.$auth = result; 
      }
    ) 

user.service.ts

<img [src]="'http://clinic.com/img/'+$auth.profile_pic" />

**用户模型**

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

import { User } from '../model/User'; 
import { Pagination } from '../model/Pagination'; 

@Injectable({
  providedIn: 'root'
})
export class UserService {

  public root = "http://clinic.com"; 
  constructor(public http:HttpClient) { }


  authUser(): Observable<User>{
    let $url = this.root+"/ajax/get/auth user"
    return this.http.get<User>($url); 
  }
}

** JSON响应(如果您感兴趣的话)

export class User {
  constructor(
    public id: number,
    public worker_id: string,
    public first_name: string,
    public father_name: string,
    public grand_father_name: string,
    public gender: string,
    public role_id: number,
    public email: string,
    public phone: string,
    public role?: number,
    public profile_pic?: string,
    public isFirstTime?: number,
    public created_at?: string,
    public updated_at?: string ){}

}

那么这段代码是什么问题,或者是加载图像的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您应该在组件上创建:

________________________________________________________________________
Input                        |  Inner            | Output
------------------------------------------------------------------------
                             |
(Parent.method -> broadType) |-> (Child.method2 -> narrowedType)
                             |
------------------------------------------------------------------------

在html上:

Public avatarUrl: string;

最后:

<img [src]="avatarUrl">