Angular4:注入Service后组件消失
Angular 4: Component disappears after injecting Service
我在 Angular 4
中遇到了关于 Components
和 Services
的问题。
所以我得到了 CustomerComponent
:
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
customers: Customer[] = [];
constructor() { }
和 Customer Model
:
export class Customer {
constructor(
public id: number,
public firstName: string,
public lastName: string
) { }
}
和 CustomerService
:
@Injectable()
export class CustomerService {
private customersUrl = 'http://localhost:9090/customer';
constructor(private http: Http) { }
// Get all customers
getCustomers(): Promise<Customer[]> {
return this.http.get(this.customersUrl)
.toPromise()
.then(response => response.json() as Customer[])
.catch(this.handleError);
}
现在我想在 AppComponent 中显示 CustomerComponent。
它通过添加 <app-customer></app-customer>
显示:customer works
.
但是当我像这样将 CustomerService
添加到 CustomerComponent
的构造函数中时:
constructor(private customerService: CustomerService) { }
customer works
不再显示,我也没有在控制台中收到错误消息。所以我不知道问题是什么。有人可以帮忙吗?谢谢
将您的服务添加到应用程序模块。
providers: [
CustomerService
],
我发现了问题所在。我忘记在 AppModule
中导入 HttpModule
。但是我仍然不知道为什么我在任何地方都没有看到错误...
我在 Angular 4
中遇到了关于 Components
和 Services
的问题。
所以我得到了 CustomerComponent
:
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
customers: Customer[] = [];
constructor() { }
和 Customer Model
:
export class Customer {
constructor(
public id: number,
public firstName: string,
public lastName: string
) { }
}
和 CustomerService
:
@Injectable()
export class CustomerService {
private customersUrl = 'http://localhost:9090/customer';
constructor(private http: Http) { }
// Get all customers
getCustomers(): Promise<Customer[]> {
return this.http.get(this.customersUrl)
.toPromise()
.then(response => response.json() as Customer[])
.catch(this.handleError);
}
现在我想在 AppComponent 中显示 CustomerComponent。
它通过添加 <app-customer></app-customer>
显示:customer works
.
但是当我像这样将 CustomerService
添加到 CustomerComponent
的构造函数中时:
constructor(private customerService: CustomerService) { }
customer works
不再显示,我也没有在控制台中收到错误消息。所以我不知道问题是什么。有人可以帮忙吗?谢谢
将您的服务添加到应用程序模块。
providers: [
CustomerService
],
我发现了问题所在。我忘记在 AppModule
中导入 HttpModule
。但是我仍然不知道为什么我在任何地方都没有看到错误...