【问题标题】:ngOninit not getting called angular 2 expressngOninit 没有被称为 angular 2 express
【发布时间】:2018-02-13 09:51:21
【问题描述】:

我不知道,但是发生了一些奇怪的事情,我参考了“Angular.io”上提供的默认代码来执行角度服务调用,但是有些 ngOninit 方法没有被调用。 我还实现了来自 OnInit 的组件。并将@Injectable 添加到 user.services.ts。但仍然不知道我哪里错了。
以下是参考代码。

app.component.ts

//app.components.ts

import { Component } from '@angular/core';
import {User} from './user';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
 title = 'Society CRM';
}

user.ts

export class User
{
  _id : string;
  name: string;
  email: string;
  username: string;
  password: string;
  phone: string;
  address: string;
  role: string;
  created_date: string; 
}

user-list.component.ts

import {Component,OnInit} from '@angular/core';
import {User} from './user';
import {UserService} from './user.service';
import { Headers, RequestOptions } from '@angular/http';
@Component({
 selector:'user-list',
 templateUrl:'./user-list.html',
 providers: [ UserService ]
})

export class UserListComponent implements OnInit{
errorMessage: string;
users: User[];
mode = 'Observable';
constructor (private userService: UserService) {};
ngOnInit() { 
 this.getUsersList();
 alert('here');         
}
getUsersList() {  
  return this.userService.getUsersList()
                 .subscribe(
                   users => this.users = users,
                   error =>  this.errorMessage = <any>error);
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { UserListComponent }  from './user-list.component';
import { UserService } from './user.service';
import { FormsModule }   from '@angular/forms'; // <-- NgModel lives here

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

user.service.ts

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import {User} from './user';
import { Headers, RequestOptions } from '@angular/http';
@Injectable()
export class UserService
{
        constructor (private http:Http){}
        private api_url = "http://localhost:3000/api/";
        getUsersList() : Observable<User[]>
        {
            let headers = new Headers();
            headers.append('Access-Control-Allow-Origin', '*');
            headers.append('Access-Control-Allow-Credentials', 'true');
            headers.append('Access-Control-Allow-Methods', 'GET');
            headers.append('Access-Control-Allow-Headers', 'Content-Type');
            let options = new RequestOptions({headers: headers});
            return this.http.get(this.api_url+'getUsersList',options)
                .map(this.extractData)
                .catch(this.handleError);

        }

        private extractData(res: Response) {
            let body = res.json();
            return body.data || {};
        }
        private handleError(error: Response | any) {
            // In a real world app, you might use a remote logging infrastructure
            let errMsg: string;
            if (error instanceof Response) {
                const body = error.json() || '';
                const err = body.error || JSON.stringify(body);
                errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
                errMsg = error.message ? error.message : error.toString();
            }
            console.error(errMsg);
            return Observable.throw(errMsg);
        }
}  

我不知道上面的代码到底发生了什么,萤火虫控制台或浏览器控制台上没有显示错误。任何帮助将不胜感激

【问题讨论】:

  • 控制台有错误吗?
  • 控制台未显示任何错误
  • 你怎么知道ngOnInit方法没有被调用?您是否在 app.component.html 中添加了用户 -ist.component?
  • 发布 app.component.html
  • {{title}}

标签: node.js angular typescript express


【解决方案1】:

通过添加以下代码更改您的 app.component.html 代码:

&lt;user-list&gt;&lt;/user-list&gt;

没有调用 OnInit,因为您不使用 user-list.component。

【讨论】:

  • 我们都会犯这样的错误!我们不要。它会变得尴尬一段时间。 :)
【解决方案2】:

检查您是否确实使用了该组件... 例如,标签&lt;user-list&gt;&lt;/user-list&gt; 是否定义在您的 html 中?

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2018-09-01
    • 2016-06-26
    • 1970-01-01
    • 2018-06-12
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多