[英]connecting angular web app to firebase
I watn to connect my web application to firebase,and I have VPN but after running, my dashboard component is not displayed and there are some errors : 我想将我的Web应用程序连接到firebase,并且我有VPN,但是运行后,我的仪表板组件未显示,并且出现了一些错误:
An error occurred :Response app/hero.service.js:57 ERROR Error:node_modules/@angular/core/bundles/core.umd.js:1091 Uncaught (in promise): Response with status: 404 Not Found for URL: https://my firebase database name /.json 发生错误:响应app / hero.service.js:57错误错误:node_modules/@angular/core/bundles/core.umd.js:1091未捕获(承诺):状态为:404找不到URL: https的响应://我的 Firebase数据库名称/.json
This is my code: DashboardComponent: 这是我的代码: DashboardComponent:
import { Component, OnInit } from '@angular/core';
import {Http} from '@angular/http';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: [ './dashboard.component.css' ]
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) { }
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}
}
hero.service.ts hero.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
@Injectable()
export class HeroService {
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = private heroesUrl = "https://tour-of-heroes-bcc7b.firebaseio.com/.json"; // URL to web api
constructor(private http: Http) { }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
getHero(id: number): Promise<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Hero)
.catch(this.handleError);
}
delete(id: number): Promise<void> {
const url = `${this.heroesUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
create(name: string): Promise<Hero> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as Hero)
.catch(this.handleError);
}
update(hero: Hero): Promise<Hero> {
const url = `${this.heroesUrl}/${hero.id}`;
return this.http
.put(url, JSON.stringify(hero), {headers: this.headers})
.toPromise()
.then(() => hero)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
index.html 的index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>Angular Tour of Heroes</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfills -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
<body>
<my-app>Loading...</my-app>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "my firebase project apikey",
authDomain: "my firebase projec domain name",
databaseURL: "my firebase projec database name",
projectId: "my firebase projec ID",
storageBucket: "my firebase projec storage",
messagingSenderId: "my firebase projec senderId"
};
firebase.initializeApp(config);
</script>
</head>
</body>
</html>
app.module.ts app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from './hero.service';
import { HeroSearchComponent } from './hero-search.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
AppRoutingModule
],
declarations: [
AppComponent,
DashboardComponent,
HeroDetailComponent,
HeroesComponent,
HeroSearchComponent
],
providers: [ HeroService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
尝试更新url heroesUrl = "https://tour-of-heroes-bcc7b.firebaseio.com/.json"
。
First of all, I see that you have used InMemoryWebApi
. 首先,我看到您已经使用了InMemoryWebApi
。 You need to remove the following line from your NgModule
, it will interfere with your "real" http-requests. 您需要从NgModule
删除以下行,这会干扰您的“实际” http请求。 So remove from NgModule
the following line: 因此,从NgModule
删除以下行:
InMemoryWebApiModule.forRoot(InMemoryDataService)
Then Notice the extra private heroesUrl
in your Service: 然后注意您服务中额外的private heroesUrl
:
private heroesUrl = private heroesUrl = "https://tour-of-heroes-bcc7b.firebaseio.com/.json";
should be: 应该:
private heroesUrl = "https://tour-of-heroes-bcc7b.firebaseio.com/.json";
Next your getHeroes
function in your service. 接下来,服务中的getHeroes
函数。 The JSON you are receiving, is an array, so there is no object data
in your response, that would contain the array you are looking for, so change: 您接收的JSON是一个数组,因此响应中没有对象data
,该对象data
将包含您要查找的数组,因此请更改:
.then(response => response.json().data as Hero[])
to 至
.then(response => response.json() as Hero[])
I think I have then pinpointed the errors (hopefully). 我想我已经找到了错误(希望如此)。 Here's a little 有一点
The new error slice is not a function
is caused by you having changed the request url, so the data changed and now we are no longer dealing with an array, but an object of objects. 新的错误slice is not a function
由您更改请求url引起的,因此数据已更改,现在我们不再处理数组,而是对象的对象。 Therefore you need to create a loop and extract each object and push them to your heroes
array. 因此,您需要创建一个循环并提取每个对象,然后将其推入heroes
数组。 So your subscribe would then look like this: 因此,您的订阅将如下所示:
this.heroService.getHeroes()
.then(data => {
// iterate the object and push each object from inside that object to your array
for(let obj in data) {
this.heroes.push(data[obj])
}
console.log(this.heroes)
this.heroes = this.heroes.slice(1, 5)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.