首页 > 解决方案 > Angular 6组件未显示

问题描述

我昨天刚开始学习 Angular,所以如果我遗漏了一些明显的东西,我深表歉意,但是我试图在 app.component.html 上显示一个组件,但是它没有显示出来。

我要显示的组件的 TS 文件:

import { Component, OnInit } from '@angular/core';
import { ImageService } from '../shared/image.service';

@Component({
  selector: 'image-list',
  templateUrl: './image-list.component.html',
  styleUrls: ['./image-list.component.css']
})
export class ImageListComponent implements OnInit {

  images: any[];

  constructor(private _imageService : ImageService ) { }

  searchImages(query : string)
  {
    return this._imageService.getImage(query).subscribe
    (
      data => console.log(data),
      error => console.log(error),
      () => console.log("Request Completed!")
    );
  }

  ngOnInit() {
  } 
}

图像列表.component.html :

<button>Find Images</button>

app.component.html :

<image-list></image-list>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

图像.service.ts

import { Injectable } from "@angular/core";
import { environment } from "../../environments/environment";
import { Http, Headers } from "@angular/http";
import { map, filter, scan } from 'rxjs/operators';

@Injectable()
export class ImageService
{
    private query: string;
    private API_KEY: string = environment.API_KEY;
    private API_URL: string = environment.API_URL;
    private URL: string = this.API_URL + this.API_KEY + '&q=';

    constructor(private _http: Http) {

    }

    getImage(query)
    {
        return this._http.get(this.URL + this.query).pipe(
            map((res) => res.json));
    }
}

标签: htmlangular6

解决方案


我在尝试在其模块之外使用组件时遇到了类似的问题。在这种情况下,您必须从.module.ts导出一个组件:

@NgModule({
  // …
  declarations: [ MyComponent ],
  exports: [ MyComponent ],
  // …
})

推荐阅读